标签:on() 访问 数组参数 types start fragment declared const cat
获取反射加载类(获取类的字节码)的3种方式:
在JAVA中,解剖类Class提供的常用方法:
Class class1=Class.forName("lession_svc.lession_svc.reflact.Person"); Constructor c= class1.getDeclaredConstructor(String.class); c.setAccessible(true); //暴力破解 c.newInstance("张三");
例:
Class class1=Class.forName("lession_svc.lession_svc.reflact.Person"); Person p=(Person)class1.newInstance(); Method method= class1.getDeclaredMethod("Head", String.class); method.setAccessible(true);//打开访问权限 method.invoke(p, "李四");
获取静态方法并执行:
Class class1=Class.forName("lession_svc.lession_svc.reflact.Person"); //Person p=(Person)class1.newInstance(); Method method= class1.getMethod("Head", Integer.class); method.invoke(null, "李四");
注意:反射调用参数为数组时,反射会进行拆解。例:
Class class1=Class.forName("lession_svc.lession_svc.reflact.Person"); //Person p=(Person)class1.newInstance(); Method method= class1.getMethod("main", String[].class); method.invoke(null, (Object)new String[] {"12"}); //此处需要做参数包装,不做包装,反射会进行拆解数组参数,最终为:main(String s1), //与期望main(String [] args) 不相同
例:
@Test
public void func7() { try { Class class1=Class.forName("lession_svc.lession_svc.reflact.Person"); Person p=(Person) class1.newInstance(); Field name=class1.getField("name"); //设置字段值: name.set(p, "张飞"); //读取值 Object object=name.get(p); //获取字段类型 Class type=name.getType(); if(type.equals(String.class)) { String vString=(String) object; System.out.println(vString); } //2 . System.out.println(p.getName()); } catch (Exception e) { e.printStackTrace(); } }
例:
@Test
public void func8() { try { Class class1=Class.forName("lession_svc.lession_svc.reflact.Person"); Person p=(Person) class1.newInstance(); Field name=class1.getDeclaredField("age"); name.setAccessible(true); //设置字段值: name.set(p, 12); //读取值 Object object=name.get(p); //获取字段类型 Class type=name.getType(); if(type.equals(String.class)) { String vString=(String) object; System.out.println(vString); } //2 . System.out.println(p.getAge()); } catch (Exception e) { e.printStackTrace(); } }
标签:on() 访问 数组参数 types start fragment declared const cat
原文地址:https://www.cnblogs.com/hanlinxiaogege/p/12420980.html