Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a class literal of a known type: Class<List<String>>

Tags:

java

generics

jls

Take the following:

public Class<List<String>> getObjectType() {     // what can I return here? } 

What class literal expression can I return from this method which will satisfy the generics and compile? List.class won't compile, and neither will List.<String>class.

If you're wondering "why", I'm writing an implementation of Spring's FactoryBean<List<String>>, which requires me to implement Class<List<String>> getObjectType(). However, this is not a Spring question.

edit: My plaintive cries have been heard by the powers that be at SpringSource, and so Spring 3.0.1 will have the return type of getObjectType() changed to Class<?>, which neatly avoids the problem.

like image 752
skaffman Avatar asked Jan 06 '10 10:01

skaffman


People also ask

What is a class literal in Java?

A class literal is an expression consisting of the name of a class, interface, array, or primitive type followed by a . and the token class . The type of a class literal is Class .

What is the type of the class literal Foo class?

The non-erased type of Foo. class would be java.

How to make method generics in Java?

Generic MethodsAll generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example). Each type parameter section contains one or more type parameters separated by commas.


1 Answers

You can always cast to what you need, like this

return (Class<List<String>>) new ArrayList<String>().getClass(); 

or

return (Class<List<String>>) Collections.<String>emptyList().getClass(); 

But I assume that's not what you are after. Well it works, with a warning, but it isn't exactly "beautiful".

I just found this

Why is there no class literal for wildcard parameterized types?

Because a wildcard parameterized type has no exact runtime type representation.

So casting might be the only way to go.

like image 137
Bozho Avatar answered Oct 02 '22 10:10

Bozho