如何获取泛型函数体中的实际类型?
How to get the actual type in the body of a generic function?
代码如下:
public <K, T> Map<K, T> method1(Map<K, T> map, Class<T> entityClass){
//I need the Class instance of the actual type T here;
String name = entityClass.getClass().getName();
return map;
}
method1
中的 entityClass
参数是否多余?我可以从传递给此函数的地图实例中获取该信息吗?
像这样:
public <K, T> Map<K, T> method2(Map<K, T> map){
//Can I get T's actual type without that additonal parameter `Class<T> entityClass` ?
//I think this information is alreay provided by the map instance passed in by the caller.
//But I don't know how or even whether it is possible.
return map;
}
entityClass
参数是必需的。所有泛型类型信息都在编译时被丢弃。 (这称为 Type Erasure。)在编译器生成的字节码中,所有泛型都由它们的边界替换,如果它们是无边界的,则由 Object
替换(如 K
和 T
在您发布的代码中)。
无法在 运行 时恢复此丢弃的信息。这就是为什么在需要实际类型信息时总是使用像 entityClass
这样的额外类型参数。
代码如下:
public <K, T> Map<K, T> method1(Map<K, T> map, Class<T> entityClass){
//I need the Class instance of the actual type T here;
String name = entityClass.getClass().getName();
return map;
}
method1
中的 entityClass
参数是否多余?我可以从传递给此函数的地图实例中获取该信息吗?
像这样:
public <K, T> Map<K, T> method2(Map<K, T> map){
//Can I get T's actual type without that additonal parameter `Class<T> entityClass` ?
//I think this information is alreay provided by the map instance passed in by the caller.
//But I don't know how or even whether it is possible.
return map;
}
entityClass
参数是必需的。所有泛型类型信息都在编译时被丢弃。 (这称为 Type Erasure。)在编译器生成的字节码中,所有泛型都由它们的边界替换,如果它们是无边界的,则由 Object
替换(如 K
和 T
在您发布的代码中)。
无法在 运行 时恢复此丢弃的信息。这就是为什么在需要实际类型信息时总是使用像 entityClass
这样的额外类型参数。