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;
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;
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.