3

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;
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
Foo
  • 4,206
  • 10
  • 39
  • 54
  • 2
    The second line is type-safe. – mre May 18 '18 at 16:26
  • The first one is type safe too. This line will not compile Living lv= cls1.newInstance(); – Foo May 18 '18 at 16:29
  • 2
    Class is a generic class. Search "raw type" versus "generic type" – davidxxx May 18 '18 at 16:29
  • 1
    @Foo First line is not type-safe. It will give you warning "Class is a raw type. References to generic type Class should be parameterized" and I believe warnings are designed to be handled – Amit Bera May 18 '18 at 16:32
  • Quick comment over @davidxxx comment: "Raw types refer to using a generic type without specifying a type parameter. For example, List is a raw type, while List is a parameterized type." – carloswm85 Nov 25 '20 at 10:56

1 Answers1

1

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.

ernest_k
  • 44,416
  • 5
  • 53
  • 99