反射的一些理解

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值