1 调用运行时类中指定属性
/*
* 获取public权限的属性值
*/
public static void test01() throws Exception {
Class clazz = PersonFull.class;
// 实例化对象
PersonFull p1 = (PersonFull) clazz.newInstance();
// 获取属性:只能获取public权限的属性值,但是在实际开发中很少有属性值设置为public权限的,因此该方法仅了解即可
Field id = clazz.getField("id");
// 设置属性值:参数1_对象,参数2_设置的值
id.set(p1, 1001);
// 获取属性值
System.out.println(id.get(p1));
}
/*
* 获取private权限的属性值
*/
public static void test02() throws Exception {
Class clazz = PersonFull.class;
// 实例化对象
PersonFull p1 = (PersonFull) clazz.newInstance();
// 获取private权限的属性
Field name = clazz.getDeclaredField("name");
// 设置当前属性可以被访问
name.setAccessible(true);
// 设置属性值
name.set(p1, "Tom");
// 获取属性值
System.out.println(name.get(p1));
}
2 调用运行时类中指定方法
/*
* 调用非静态私有方法:需要获取类的对象
*/
public static void test01() throws Exception {
Class<PersonFull> clazz = PersonFull.class;
// 实例化对象
PersonFull p1 = (PersonFull) clazz.newInstance();
// 获取方法:参数_1:方法名,参数_2:参数列表的类型
Method show = clazz.getDeclaredMethod("show", String.class);
// 调用私有方法时设置为可访问(public权限的方法不需要)
show.setAccessible(true);
// 调用方法,并获取方法的返回值
String nation = (String)show.invoke(p1, "USA");
System.out.println(nation);
}
/*
* 调用静态方法:不需要获取类的对象
*/
public static void test02() throws Exception{
Class<PersonFull> clazz = PersonFull.class;
// 获取方法
Method disDesc = clazz.getDeclaredMethod("disDesc", String.class);
// 设置为可访问
disDesc.setAccessible(true);
// 调用方法并获取返回值
String name = (String)disDesc.invoke(clazz, "Tom");
System.out.println(name);
}
3 调用运行时类中构造器
public static void test01() throws Exception{
Class<PersonFull> clazz = PersonFull.class;
// 获取private权限的构造器
Constructor<PersonFull> constructor = clazz.getDeclaredConstructor(String.class);
// 设置可访问的权限
constructor.setAccessible(true);
// 创建PersonFull的实例
PersonFull person = constructor.newInstance("Tom");
System.out.println(person);
}