Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Class and Class<?>

Tags:

java

generics

What is the difference between a Class and a Class<?> declaration.

  • Class a;
  • Class<?> b;
like image 775
sengs Avatar asked Jun 17 '09 13:06

sengs


People also ask

What is the difference between class and class?

Class is a Java class just like Object and String are classes. In short, both are essentially the same, but you can keep a reference of a String. class object using the Class class.

What is the difference between :: class and :: class Java in Kotlin?

It is Kotlin Reflection API, that can handle Kotlin features like properties, data classes, etc. By using ::class. java , you get an instance of Class. It is Java Reflection API, that interops with any Java reflection code, but can't work with some Kotlin features.

What is difference between class and function?

Functions do specific things, classes are specific things. Classes often have methods, which are functions that are associated with a particular class, and do things associated with the thing that the class is - but if all you want is to do something, a function is all you need.


2 Answers

It's the same as with all generic and raw types:

Class          // An unknown class (raw type) Class<?>       // An unknown class (generic version) Class<String>  // The String class 

In this special case there's no much practical difference between Class and Class<?> because they both denote an unknown class. Depending on the existing declarations the compiler can demand a generic type instead of a raw type.

But: Since Java 1.5 you should use the generic form wherever possible. Class<?> clearly states that you mean "an unknown class", Class<String> cleary states that you mean the String class. A raw Class could mean both.

In the end it makes not much of a difference to the compiler but it makes a huge difference in making the intentions of your code more understandable and maintainable.

like image 139
Daniel Rikowski Avatar answered Sep 28 '22 08:09

Daniel Rikowski


Class javadoc:

Type Parameters: T - the type of the class modeled by this Class object. For example, the type of String.class is Class<String>. Use Class<?> if the class being modeled is unknown.

Use of Class without the type parameter is similar to using any generic class (Map, List, etc.) without the type parameter - either it's a pre-1.5 legacy usage or it's just a segment of code that does not care about unchecked type casting.

like image 30
matt b Avatar answered Sep 28 '22 09:09

matt b