Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class vs Class<T> in Java [duplicate]

Tags:

java

generics

Is there a difference between these two lines of code? Or is the first line just a shorthand way or writing the second line?

Class cls1 = Person.class;
Class<Person> cls2 = Person.class;
like image 245
Foo Avatar asked Jun 21 '26 19:06

Foo


1 Answers

The difference between the two is only significant at compile-time.

Class<Person> allows type safety and static type checking. For example, the following code is perfectly understood by the compiler and reduces unnecessary type casts. Additionally, it's type-safe:

Class<Person> personClass = Person.class;
Person person = personClass.newInstance(); //Great! Return type is Person

However, this same version using the raw Class type doesn't give type safety benefits of the above code:

Class personClass2 = Person.class;
Person person2 = personClass2.newInstance(); //error

The compiler complains about the last statement:

Type mismatch: cannot convert from Object to Person

Although it's effectively the same Class instance, the generic version allows static type checking, which provides safety and avoids unnecessary type casts.

At runtime, however, the two are basically equivalent.

System.out.println(personClass == personClass2); //true
System.out.println(personClass == person.getClass()); //true

When used with reflection or otherwise inspected, the two have no difference because the instance is the same and generic types are erased.

like image 102
ernest_k Avatar answered Jun 23 '26 09:06

ernest_k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!