创建对象实例会导致类加载,通过类加载器对字节码文件进行加载,类加载会先在方法去生成类字节码的二进制数据/元数据,然后在堆内生成Class类对象,成员变量、构造器、成员方法、注解、泛型等等都用相应的对象数组进行存储。
Cat.java
package com.reflect_; /** * Created on 2021/6/30. * * @author Ryan_小王 */ public class Cat { private String name = "招财猫"; public int age = 10; public Cat() {} public Cat(String name) { this.name = name; } public void hi() { System.out.println("hi" + name); } }
ReflectQuestion.java
package com.reflect_; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Properties; /** * Created on 2021/6/30. * * @author Ryan_小王 */ public class ReflectQuestion { public static void main(String[] args) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException { //传统方法 Cat cat = new Cat(); cat.hi(); //1.使用Properties类,可以读写配置文件 Properties properties = new Properties(); properties.load(new FileInputStream("src\\re.properties")); String classfullpath = properties.get("classfullpath").toString(); String methodName = properties.getProperty("method").toString(); System.out.println("classfullpath=" + classfullpath); System.out.println("method=" + methodName); //2.使用反射机制解决 //(1)加载类,返回Class类型的对象cls Class cls = Class.forName(classfullpath); //(2)通过cls得到你加载的类的对象实例 Object o = cls.newInstance(); System.out.println("o的运行类型=" + o.getClass()); //(3)通过cls得到你加载的类的methodName "hi"的方法对象 // 即:在反射中,可以把方法视为对象(万物皆对象) Method method1 = cls.getMethod(methodName); //(4)通过method1调用方法:即通过方法对象来实现调用方法 System.out.println("=================================="); method1.invoke(o); //传统方法 对象.方法(),反射机制 方法.invoke(对象) //(5)Field:类的成员变量,getField不能得到私有属性 Field nameField = cls.getField("age"); System.out.println(nameField.get(o)); //(6)Constructor: Constructor constructor = cls.getConstructor(); System.out.println(constructor); Constructor constructor2 = cls.getConstructor(String.class); System.out.println(constructor2); //Cat(String name) } }