What does Class<?> mean in Java?

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.


It means your Class reference can hold a reference to any Class object.

It's basically the same as "Class" but you're showing other people who read your code that you didn't forget about generics, you just want a reference that can hold any Class object.

Bruce Eckel, Thinking in Java:

In Java SE5, Class<?> is preferred over plain Class, even though they are equivalent and the plain Class, as you saw, doesn’t produce a compiler warning. The benefit of Class<?> is that it indicates that you aren’t just using a non-specific class reference by accident, or out of ignorance. You chose the non-specific version.


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