What does Class<?> mean in Java?
Solution 1:
Class
is a parameterizable class, hence you can use the syntax Class<T>
where T
is a type. By writing Class<?>
, you're declaring a Class
object which can be of any type (?
is a wildcard). The Class
type is a type that contains meta-information about a class.
It's always good practice to refer to a generic type by specifying his specific type, by using Class<?>
you're respecting this practice (you're aware of Class
to be parameterizable) but you're not restricting your parameter to have a specific type.
Reference about Generics and Wildcards: http://docs.oracle.com/javase/tutorial/java/generics/wildcards.html
Reference about Class
object and reflection (the feature of Java language used to introspect itself): https://www.oracle.com/technetwork/articles/java/javareflection-1536171.html
Solution 2:
This <?>
is a beast. It often leads to confusion and errors, because, when you see it first, then you start believing, <?>
is a wildcard for any java type. Which is .. not true. <?>
is the unknown type, a slight and nasty difference.
It's not a problem when you use it with Class
. Both lines work and compile:
Class anyType = String.class;
Class <?> theUnknownType = String.class;
But - if we start using it with collections, then we see strange compiletime errors:
List<?> list = new ArrayList<Object>(); // ArrayList<?> is not allowed
list.add("a String"); // doesn't compile ...
Our List<?>
is not a collection, that is suitable for just any type of object. It can only store one type: the mystic "unkown type". Which is not a real type, for sure.