Malka
Malka

Reputation: 63

java.lang.Class and generics

On this gwt javadoc page http://www.gwtproject.org/javadoc/latest/com/google/gwt/core/client/GWT.html java.lang.Class<?> is passed as parameter to the create function. How is this valid?.. I could understand something like create(List<Class> classLiteral) or create(java.lang.Class classLiteral) but how the way it is used there confuses me greatly. Clarifications are much appreciated

Upvotes: 0

Views: 1269

Answers (2)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280167

java.lang.Class<?> is the full type declaration of the instance. It is equivalent to

import java.lang.Class;

...

static <T> T create(Class<?> classLiteral) ...

They are just being thorough in the javadoc. java.lang.Class is a java class that represents classes. You can read its javadoc here.

You can access the Class object of a class with

YourClass.class // where class is a reserved java keyword will return an instance of type Class<YourClass>

If you have an instance

YourClass yourInstance = ...
yourInstance.getClass(); // will return an instance of type Class<YourClass>

If <?> is confusing you, it's known as a wildcard. You can read more about it here.

Upvotes: 4

GrandpaJake
GrandpaJake

Reputation: 21

In this situation, the method calls for a class literal, not an instance of a class. This means you are passing an actual class to the method instead of an instance of a class.

An example of this is if you were to call:

create(MyClass.class);

Here, you're passing a Class object, but not an instance of MyClass. So, the create method is asking for a Class object, not an instance of whatever Class you pass into it.

If it were class(java.lang.Class classLiteral), then it would be calling for an instance of any object that extends class.

Upvotes: 2

Related Questions