Get generic class at compile time

前端 未结 1 1822
被撕碎了的回忆
被撕碎了的回忆 2021-01-19 06:12

While I know you cannot actually get the type of a generic at runtime because of type erasure, I was wondering if it is possible to get it at compile time.

c         


        
1条回答
  •  不要未来只要你来
    2021-01-19 06:37

    Since generic types are subjected to erasure, you will need to specify the java.lang.Class somewhere in the code. One way is to pass it to a generic method:

    ObjType obj = /*...*/;
    handleObj(obj, SubObjType.class);
    
    // ...
    
    private  void handleObj(ObjType obj,
                                               ObjectHandle handle,
                                               Class handleableObjClass) {
        if (handleableObjClass.isInstance(obj)) {
            handle.setObj(handleableObjClass.cast(obj));
        }
    }
    

    If you don't know what subclasses of ObjType you're looking for, you will need to add a reifiable Class property to ObjectHandle, similar to how java.util.EnumSet and java.util.EnumMap do it:

    class ObjectHandle {
    
        T obj;
    
        private final Class objectClass;
    
        ObjectHandle(Class cls) {
            objectClass = Objects.requireNonNull(cls);
        }
    
        Class getObjectClass() {
            return objectClass;
        }
    
        void setObj(T o) {
            obj = o;
        }
    }
    
    // ...
    ObjectHandle handle = new ObjectHandle();
    // ...
    
    ObjectType obj = /*...*/;
    if (handle.getObjectClass().isInstance(obj)) {
        handle.setObj(handle.getObjectClass().cast(obj));
    }
    

    0 讨论(0)
提交回复
热议问题