- 反射,可以在运行时期动态创建对象;获取对象的属性、方法;
1 public class Admin { 2 3 // Field 4 private int id = 1000; 5 private String name = "匿名"; 6 7 // Constructor 8 public Admin(){ 9 System.out.println("Admin.Admin()"); 10 } 11 public Admin(String name){ 12 System.out.println("Admin.Admin()" + name); 13 } 14 15 // Method 16 public int getId() { 17 return id; 18 } 19 public void setId(int id) { 20 this.id = id; 21 } 22 public String getName() { 23 return name; 24 } 25 public void setName(String name) { 26 this.name = name; 27 } 28 29 } 30 31 32 // 反射技术 33 public class App { 34 35 // 1. 创建对象 36 @Test 37 public void testInfo() throws Exception { 38 // 类全名 39 String className = "cn.itcast.c_reflect.Admin"; 40 // 得到类字节码 41 Class<?> clazz = Class.forName(className); 42 43 // 创建对象1: 默认构造函数简写 44 //Admin admin = (Admin) clazz.newInstance(); 45 46 // 创建对象2: 通过带参数构造器创建对象 47 Constructor<?> constructor = clazz.getDeclaredConstructor(String.class); 48 Admin admin = (Admin) constructor.newInstance("Jack"); 49 50 } 51 @Test 52 //2. 获取属性名称、值 53 public void testField() throws Exception { 54 55 // 类全名 56 String className = "cn.itcast.c_reflect.Admin"; 57 // 得到类字节码 58 Class<?> clazz = Class.forName(className); 59 // 对象 60 Admin admin = (Admin) clazz.newInstance(); 61 62 // 获取所有的属性名称 63 Field[] fs = clazz.getDeclaredFields(); 64 // 遍历:输出每一个属性名称、值 65 for (Field f : fs) { 66 // 设置强制访问 67 f.setAccessible(true); 68 // 名称 69 String name = f.getName(); 70 // 值 71 Object value = f.get(admin); 72 73 System.out.println(name + value); 74 } 75 } 76 77 @Test 78 //3. 反射获取方法 79 public void testMethod() throws Exception { 80 81 // 类全名 82 String className = "cn.itcast.c_reflect.Admin"; 83 // 得到类字节码 84 Class<?> clazz = Class.forName(className); 85 // 对象 86 Admin admin = (Admin) clazz.newInstance(); 87 88 // 获取方法对象 public int getId() { 89 Method m = clazz.getDeclaredMethod("getId"); 90 // 调用方法 91 Object r_value = m.invoke(admin); 92 93 System.out.println(r_value); 94 } 95 96 }