package com.atguigu.java;
import org.junit.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author Dxkstart
* @create 2021-11-23-18:15
*/
public class ReflectionTest {
//反射之后
@Test
public void test1() throws Exception {
Class<Person> clazz = Person.class;
//1.通过反射,创建Person类的对象
Constructor<Person> constructor = clazz.getConstructor(String.class, int.class);
Person tom = constructor.newInstance("Tom", 12);
System.out.println(tom.toString());
//2.通过反射,调用对象指定的属性、方法
//调用属性
Field age = clazz.getDeclaredField("age");
age.set(tom,10);
System.out.println(tom.toString());
//调用方法
Method show = clazz.getDeclaredMethod("show");
show.invoke(tom);
System.out.println("************************");
//通过反射,可以调用Person类额私有结构的,比如:私有构造器,方法,属性
//私有构造器
Constructor<Person> con1 = clazz.getDeclaredConstructor(String.class);
con1.setAccessible(true);
Person jerry = con1.newInstance("Jerry");
System.out.println(jerry);
//私有属性
Field name = clazz.getDeclaredField("name");
name.setAccessible(true);
name.set(jerry,"Mack");
System.out.println(jerry);
//私有方法
Method showNation = clazz.getDeclaredMethod("showNation", String.class);
showNation.setAccessible(true);
String nation = (String) showNation.invoke(jerry,"china");
System.out.println(nation);
}
}