反射的一些理解

本文展示了Java中如何进行反射和自省操作,包括通过Introspector获取BeanInfo,遍历并修改对象属性,以及使用PropertyDescriptor访问和设置方法。同时,文章还提到了获取Class对象的三种方式,并给出了使用反射获取并操作字段的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 反射和自省(Reflection 和 Introspection )

自省

@Test
	public void test01() throws Exception {
		BeanInfo beanInfo = Introspector.getBeanInfo(A.class);
		System.out.println("beanInfo:	"+beanInfo);
		A test0 = new A(0, "test0");
		for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) {
			System.out.println("=========================");
			System.out.println(propertyDescriptor.getName());
			Method readMethod = propertyDescriptor.getReadMethod();
			Method writeMethod = propertyDescriptor.getWriteMethod();
			//ps: invoke 中传递的参数是对象,而不是对象类型
			Object invoke = readMethod.invoke(test0);
			System.out.println(invoke);
			System.out.println("调用set方法后");
			String name = propertyDescriptor.getName();
			System.out.println("propertyDescriptor.getName():	" + name);
			if (name.equals("age")) {
				Object test = writeMethod.invoke(test0, 1);
			}else if (name.equals("class")) {
				continue;
			}else {
				Object test = writeMethod.invoke(test0, "test1");
			}
			Object invoke1 = readMethod.invoke(test0);
			System.out.println(invoke1);
			Method readMethod1 = propertyDescriptor.getReadMethod();
			Object invoke2 = readMethod1.invoke(test0);
			System.out.println(invoke2);
			System.out.println("=========================");
		}
		String abc = Introspector.decapitalize("abc");
		System.out.println("字符串转换为java变量名称大写:	"+abc);
	}

2. 获取Class类的方法

		//获取Class对象的三种方法
        Test test = new Test();
        Class c1 = test.getClass();
        Class c2=Test.class;
        Class c3=Class.forName("ClassTest.Test");

3.反射的使用

Field[] fields = oldBean.getClass().getDeclaredFields();
for (Field field : fields) {
PropertyDescriptor pd1 = new PropertyDescriptor(field.getName(), clazz1);
Method getMethod1 = pd1.getReadMethod();
Object o1 = getMethod1.invoke(oldBean);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值