Generics and Class.forName

后端 未结 6 1670
礼貌的吻别
礼貌的吻别 2020-12-09 02:53

I would like to create an instance of a specified class using its name. My code is shown below.

I get a compiler warning. Am I doing this the right way? Is it even p

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-09 03:58

    I found an interesting thing: Type can be converted to Class directly if it is not a generic type. But i still can not Class.forName("java.util.List").

    import java.lang.reflect.*;
    import java.util.*;
    
    public class Main {
        public void func(List> listlist, Map> list, String s) {}
    
        public static void main(String[] args) throws ClassNotFoundException {
            Method m = Main.class.getDeclaredMethods()[1];
    
            Type t0 = m.getGenericParameterTypes()[0];
            boolean b0 = t0 instanceof Class;
    
            boolean b01 = ((ParameterizedType)t0).getRawType() instanceof Class;
    
            Type t1 = m.getGenericParameterTypes()[2];
            boolean b1 = t1 instanceof Class;
        }
    }
    

提交回复
热议问题