美文网首页
关于反射的使用

关于反射的使用

作者: 手打小黑板 | 来源:发表于2020-02-12 10:10 被阅读0次
    Class xlass = Class.forName(classPath);
    
                System.out.println(xlass.getName());
                for(Field method : xlass.getDeclaredFields()){
                    System.out.println(method.getName());
    
                }
    
                Constructor<ReflectionClass> crc = xlass.getDeclaredConstructor(String.class);
                crc.setAccessible(true);//可访问调用私有成员
                ReflectionClass rc = crc.newInstance("One World One Ghost");
                *//*Class[] cArr = {String.class,int.class,boolean.class};
                Method method = xlass.getMethod("test",cArr);
                Object[] oArr = {"NOTO",123,true};
                method.invoke(null,oArr);*//*
    
    
                Method m = xlass.getMethod("test", String.class, int.class, boolean.class);
                m.invoke(ReflectionClass.class,"HHH",333,false);
    
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
    

    反射中获取泛型参数信息

            Method m = null;
            try {
                m = ReflectionClass.class.getMethod("test", Map.class, List.class);
                Type[] mType = m.getGenericParameterTypes();
    
                for(Type t : mType){
                    for(Type p :((ParameterizedType)t).getActualTypeArguments()){
                        System.out.println(p);
                    }
    
                }
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
    
    

    相关文章

      网友评论

          本文标题:关于反射的使用

          本文链接:https://www.haomeiwen.com/subject/nmyqfhtx.html