除了之前使用的通过 new 的方式创建对象,我们还可以使用反射的方法在运行的时候来创建对象
Person.java
package test23;/*** Created By Intellij IDEA** @author Xinrui Yu* @date 2021/12/6 15:23 星期一*/public class Person {private String name;private int age;public Person() {}public Person(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +'}';}public void speak(){System.out.println("人可以说话");}private void show(){System.out.println("我是一个私有的show方法");}}
package test23;import org.junit.Test;import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;/*** Created By Intellij IDEA** @author Xinrui Yu* @date 2021/12/6 15:23 星期一*/public class ReflectionTest {@Testpublic void test1() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {Class myClass = Person.class;Person person = null;// 1、获得构造器Constructor constructor = myClass.getConstructor(String.class,int.class);// 2、通过构造器构造对象Object o = constructor.newInstance("yxr", 19);// 3、判断一个是不是我们需要的 Person 类型if(o instanceof Person){System.out.println("创建的对象是 Person 类型");person = (Person) o;}else{System.out.println("创建的对象不是 Person 类型");}// 4、获得对象中的所有属性Field[] fields = myClass.getDeclaredFields();for (Field field : fields) {System.out.println("属性名:" + field.getName());}// 5、获得对象中的所有声明的方法Method[] methods = myClass.getDeclaredMethods();for (Method method : methods) {System.out.println("方法名:" + method.getName());}// 6、调用某一个具体的方法Method func = myClass.getMethod("speak");func.invoke(person);// 7、不同于普通的new Person(),通过反射来创建对象可以直接访问到对象中的的私有属性/方法// 这里尝试通过反射来调用 Person 中私有的show()方法Method method = myClass.getDeclaredMethod("show");// 需要把访问权限设置成 truemethod.setAccessible(true);method.invoke(person);}}

不同于普通的new Person(),通过反射来创建对象可以直接访问到对象中的的私有属性
method.setAccessible(true)

如果方法有返回值的话,也可以进行接收
