package reflection2; import static org.junit.Assert.assertArrayEquals; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.junit.jupiter.api.Test; import reflection1.Person; /* * 调用运行时类中指定的结构:属性,方法,构造器 * */ public class ReflectionTest { /* * * * */ @Test public void test1() throws NoSuchFieldException, SecurityException, InstantiationException, IllegalAccessException { Class clazz = Person.class; //创建运行时类对象 Person person = (Person)clazz.newInstance(); //获取指定变量名的属性 Field name = clazz.getDeclaredField("name"); //将权限修改为可获得 name.setAccessible(true); //设置当前对象的属性值:set()方法:参数1:指明设置哪个对象的属性,参数2:将属性设置为多少 name.set(person, "Tom"); /* * 获取当前属性值get():参数1:获取哪个对象的属性值 * */ int pAge = (int)name.get(person); System.out.println(pAge); } /* * 操作运行时类中指定的方法 * */ @Test public void test2() throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException { Class clazz = Person.class; //创建运行时类对象 Person person = (Person)clazz.newInstance(); //获取指定的某个方法 //参数1:指明获取方法的名称,参数2:指明获取方法的形参列表 Method show = clazz.getDeclaredMethod("show", String.class); //将权限改为可访问 show.setAccessible(true); //invoke():参数1:方法调用者 参数2:给方法形参赋值的实参 //返回值 为调用的方法的返回值 String nation = (String)show.invoke(person,"CHN"); System.out.println(nation); System.out.println("*********************调用静态方法**********************"); Method showDesc = clazz.getDeclaredMethod("showDesc"); showDesc.setAccessible(true); //直接用这个类去调用就行 showDesc.invoke(Person.class); } /* * 调用运行时类的指定的构造器 * */ @Test public void test3() throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Class clazz = Person.class; //获取指定的构造器:参数:指明构造器的参数列表 Constructor constructor = clazz.getDeclaredConstructor(String.class); //将权限改为可访问 constructor.setAccessible(true); Person person = (Person)constructor.newInstance("Tom"); System.out.println( person); } }
1
原文地址:https://www.cnblogs.com/zsben991126/p/11888622.html
时间: 2024-09-29 22:19:02