Convert java.lang.reflect.Type to Class clazz

前端 未结 6 1636
闹比i
闹比i 2021-02-12 11:43

How can I convert java.lang.reflect.Type to Class clazz?

If I have one method as next which has an argument of Class

6条回答
  •  你的背包
    2021-02-12 12:12

    Using generic types in runtime is a little bit tricky in Java. And I think this is a root cause of your issue.

    1) to be sure about generic in runtime we doing like this:

    class MyClass {}
    

    and then:

    MyClass genericAwaredMyClassInctance = new MyClass(){};
    

    please pay attention to {} in the end. It means anonymous extends of MyClass. This is an important nuance.

    2) let`s improve MyClass to be able to extract the type in runtime.

    class MyClass {
    
        @SuppressWarnings("unchecked")
        protected Class getGenericClass() throws ClassNotFoundException {
            Type mySuperclass = getClass().getGenericSuperclass();
            Type tType = ((ParameterizedType)mySuperclass).getActualTypeArguments()[0];
            String className = tType.getTypeName();
    
            return (Class) Class.forName(className);
        }
    
    }
    

    and finally, use it like this:

    MyClass genericAwaredMyClassInctance = new MyClass(){};
    
    assert(genericAwaredMyClassInctance.getGenericClass() == TargetType.class)
    

提交回复
热议问题