java学习笔记-反射
反射: 通过对象获取类的信息 构造函数 属性 方法;
获取属性:
1 public static void reflect(Object o) throws Exception{ 2 //根据对象获取类 3 Class a = o.getClass(); 4 //获取所有访问权限为public的属性 5 Field[] f1 = a.getFields(); 6 System.out.println("公共属性:"+Arrays.toString(f1)); 7 //获取本类所有的属性 8 Field[] f2=a.getDeclaredFields(); 9 System.out.println("所有方法:"+Arrays.toString(f2)); 10 Field f3 = a.getDeclaredField("name"); 11 f3.setAccessible(true); 12 //给属性设置值 13 f3.set(o,"liuxiong"); 14 //获取属性值 15 Object ss = f3.get(o); 16 } 17 public static void main(String[] args) throws Exception{ 18 String s = "com.Test"; 19 Object o = Class.forName(s).newInstance(); 20 reflect(o); 21 }
获取方法:
public static void reflect(Object o) throws Exception{ //根据对象获取类 Class a = o.getClass(); //获取所有访问权限为public的方法包括父类 Method[] m1 = a.getMethods(); System.out.println("公共方法:"+Arrays.toString(m1)); //获取本类所有的方法 Method[] m2=a.getDeclaredMethods(); System.out.println("所有方法:"+Arrays.toString(m2)); //调用私有方法 Method m3 = a.getDeclaredMethod("say",String.class); m3.setAccessible(true); m3.invoke(o, "在干嘛"); //调用公有方法 Method m5 = a.getMethod("setName",String.class); m5.invoke(o, "liuxiong"); Method m4 = a.getMethod("getName"); Object sss =m4.invoke(o); System.out.println(sss); } public static void main(String[] args) throws Exception{ String s = "com.Test"; Object o = Class.forName(s).newInstance(); reflect(o); }
获取构造函数:
1 public static void reflect(Object o) throws Exception{ 2 //根据对象获取类 3 Class a = o.getClass(); 4 //获取所有访问权限为public的构造函数 5 Constructor[] c1 = a.getConstructors(); 6 System.out.println("公共方法:"+Arrays.toString(c1)); 7 8 //获取本类所有的方法 9 Constructor[] c2 = a.getDeclaredConstructors(); 10 11 12 System.out.println("所有方法:"+Arrays.toString(c2)); 13 14 //diao 15 Constructor c3 = a.getDeclaredConstructor(String.class); 16 c3.setAccessible(true); 17 Object o1 = c3.newInstance("liux"); 18 System.out.println(o1); 19 } 20 public static void main(String[] args) throws Exception{ 21 String s = "com.Test"; 22 Object o = Class.forName(s).newInstance(); 23 reflect(o); 24 }
越过泛型检查:
1 public static void reflect(Object o) throws Exception{ 2 Class a = o.getClass(); 3 Method m = a.getDeclaredMethod("add", Object.class); 4 m.setAccessible(true); 5 m.invoke(o, "ssss"); 6 System.out.println(o); 7 } 8 public static void main(String[] args) throws Exception{ 9 ArrayList<Integer> list = new ArrayList<Integer>(); 10 list.add(123); 11 System.out.println(list); 12 reflect(list); 13 }

浙公网安备 33010602011771号