简体   繁体   English

如何在泛型函数的主体中获取实际类型?

[英]How to get the actual type in the body of a generic function?

Here is the code: 这是代码:

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;
}

Is that entityClass parameter in method1 redundant? method1那个entityClass参数是否多余? Can I get that info from the map instance passed to this function? 我可以从传递给此函数的地图实例中获取该信息吗?

Like this: 像这样:

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;
}

The entityClass parameter is necessary. entityClass参数是必需的。 All the generic type information is thrown away at compile time. 所有通用类型信息在编译时都会被丢弃。 (This is called Type Erasure .) In the bytecode generated by the compiler, all generic types are replaced by their bounds or by Object if they are unbounded (as are K and T in the code you posted). (这称为Type Erasure 。)在编译器生成的字节码中,所有通用类型都将被其边界或Object如果它们不受限制)替换(如您发布的代码中的KT )。

It is not possible to recover this discarded information at run time. 在运行时无法恢复此丢弃的信息。 This is why an extra type parameter like entityClass is always used when actual type information is needed. 这就是为什么当需要实际的类型信息时,总是使用额外的类型参数(例如entityClass )的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM