第四课 调用运行时类的多种结构

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);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值