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.
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 .
The non-erased type of Foo. class would be 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With