Java - 反射机制 2
package spring.classloader; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * 反射机制 * * 核心类: * Constructor : 类的构造函数反射类 * Method : 类的方法反射类 * Field : 类的成员变量反射类 * * @author 咖啡不苦 */ public class TestClassLoader { @SuppressWarnings({ "unchecked", "rawtypes" }) public static void main(String[] args) { // 直接创建实例 // People people = new People("HeYan", 20, true); // System.out.println(people.getPeople()); try { // 使用反射机制 // 通过类加载器加载 People 类对象 ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class clazz = loader.loadClass("spring.classloader.People"); // 获取类的默认构造器对象,并通过它实例化对象 Constructor con = clazz.getDeclaredConstructor((Class [])null); People people = (People) con.newInstance(); System.out.println(people.getPeople()); // 获取类的所有构造器对象 Constructor [] cons = clazz.getDeclaredConstructors(); People p2 = (People) cons[1].newInstance("He", 18, true); System.out.println(p2.getPeople()); // 通过反射方法设置属性 Method setName = clazz.getDeclaredMethod("setName", String.class); // 取消Java语言访问检查以访问private 方法 setName.setAccessible(true); setName.invoke(p2, "JJ"); System.out.println(p2.getPeople()); // 获取类的成员变量 Field fName = clazz.getDeclaredField("name"); // 取消Java语言访问检查以访问private 成员变量 fName.setAccessible(true); fName.set(p2, "Demon"); System.out.println(p2.getName()); } catch (Exception e) { e.printStackTrace(); } } }
package spring.classloader; public class People { private String name; protected int age; public boolean sex; public People() { } public People(String name, int age, boolean sex) { this.name = name; this.age = age; this.sex = sex; } public String getName() { return name; } @SuppressWarnings("unused") private void setName(String name) { this.name = name; } @SuppressWarnings("unused") public String getPeople() { int i = 0; return "Name: " + name + ", age: " + age + ", sex: " + sex + "..."; } }