I'm trying to pass a type parameter to a function
public void foo(Class<T> class){
// do something
}
it's easy if i have to pass Integer
or any simple Class
by just passing foo(ClassName.class)
but how can i pass this with generic type, i.e those class that have generic types? e.g
Map<String,Object> m = foo(Map<String,Object>.class) // achieve something like this
Map<String,Object> m = (Map<String,Object>)foo(Map.class) // instead of something like this
CodePudding user response:
Depending on what the receiver is doing, you may be able to get the necessary information from a ParameterizedType
instance. ParameterizedType
is a subclass of Type
, as is Class
, and many libraries that do binding or other reflection-intensive work use Type
instead of Class
.
In order to obtain a ParameterizedType
instance, however, you have to define a type with the correct generic parameters. This is called a "type token," and often an anonymous instance is created.
Re-write your foo()
method to inspect the class for generic type information:
<T> void foo(Class<T> clz) {
Type type = clz.getGenericSuperclass();
if (type instanceof ParameterizedType) {
ParameterizedType generic = (ParameterizedType) type;
for (Type t : generic.getActualTypeArguments()) {
System.out.println(t);
}
} else {
System.out.println(clz);
}
}
Now you can create a type token and pass it to your method:
/* This doesn't work; type parameters are erased. */
Class<?> fail = Map<String, Object>.class
class TypeToken<T> {}
Class<?> okay = new TypeToken<Map<String, Object>>() {}.getClass();
foo(okay);
CodePudding user response:
You can use getClass method.
import java.util.*;
public class Main{
public static <T> void foo(Class<T> c){
System.out.println(c);
}
public static void main(String[] args) {
Map<String,String> m = new HashMap<>();
foo(m.getClass());
}
}
Output
class java.util.HashMap