主体代码参看(反射(二))[https://www.cnblogs.com/SnailsRunning/p/10253633.html]
测试代码
package day19;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.junit.Test;
public class TestSpecial {
/**
* 调用特定的属性 ;
* @throws Exception
*/
@Test
public void method1() throws Exception {
Class clazz = Class.forName("day19.Person");
//公共的属性(public修饰);
Field field1 = clazz.getField("name");
//必须要有一个显示的空构造函数
Person p = (Person) clazz.newInstance();
System.out.println(p);
field1.set(p, "Jack");
System.out.println(p);
//所有的(public、protected、default和private)
Field field2 = clazz.getDeclaredField("age");
//这里age被private修饰所以需要设置是否可以被访问;
field2.setAccessible(true);
field2.set(p, 20);
System.out.println(p);
}
@Test
public void method2() throws Exception {
//公共方法;
Class clazz = Class.forName("day19.Person");
Method method1 = clazz.getMethod("toString");
//调用指定的带参数构造函数;
Constructor constructor = clazz.getConstructor(String.class,int.class);
Person p = (Person)constructor.newInstance("Rose",19);
method1.invoke(p);
System.out.println(p);
//该类所有的方法
//调用私有方法;
Method mehtod2 = clazz.getDeclaredMethod("display");
mehtod2.setAccessible(true);//由于display方法被private修饰,所以需要设置可访问;
mehtod2.invoke(p);
//调用带有参数的方法;
Method method3 = clazz.getDeclaredMethod("show1",String.class);
method3.invoke(p, "hello");
//调用静态方法;
Method method4 = clazz.getDeclaredMethod("show2");
method4.invoke(Person.class);
}
}
运行结果
注意
根据权限必要的时候需要设置setAccessible(true)