简体   繁体   中英

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? 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. 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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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