Get “real” class of generic type

前端 未结 5 691
傲寒
傲寒 2021-02-02 16:33

How can I get the \"real\" class of a generic type?

For Example:

public class MyClass {
    public void method(){
        //something

        S         


        
5条回答
  •  轮回少年
    2021-02-02 17:18

    Note that approaches relying on 'getClass()' on an instance received with a generic type will get the actual type of that object, which is not necessarily the generic type - which would be the type by which the caller knew the instance.

    For example, consider the case where the caller handles an object by an interface; when passing to generic constructs, the generic type will be the interface, not the instance's actual class.

    Consider the following example "Pair" class, which allows two object references to be returned through a POJO:

    public class Pair
    {
        public final U first;
        public final V second;
        public static  Pair of (U first, V second)
        {
            return new Pair (first, second);
        }
        protected Pair (U first, V second)
        {
            this.first  = first;
            this.second = second;
        }
    }
    

    We were considering how to modify the 'Pair.of()' factory function to return a Comparable Pair derived class, if U and V were both Comparable. However, while we can tell whether 'first' and 'second' are comparable using instanceof, we don't know that 'U' and 'V' are themselves comparable.

    For this to work, the exact type of Pair returned by Pair.of() must depend on the generic types, not the actual argument types.

提交回复
热议问题