反射初试

    工作中用到反射,代码记录如下

public String callXMLHandler(Object obj) throws IllegalArgumentException, IllegalAccessException{
		Class<? extends BaseRequestBean> clazz = (Class<? extends BaseRequestBean>)obj.getClass();
		Class<BaseRequestBean> clazzSuper = (Class<BaseRequestBean>) clazz.getSuperclass();//获得父类的Class
		Field field[] = clazz.getDeclaredFields();//getDeclaredFields 无法获得继承属性
		//System.out.println(field.length);
		Field fieldSuper[] = clazzSuper.getDeclaredFields();//获得父类属性
		//System.out.println(fieldSuper.length);
		XMLEntity e = new XMLEntity();
		for (Field f1 : field) {
			f1.setAccessible(true);//取消访问权限检查,以便能够访问非公共属性
			System.out.println(f1.getName()+","+f1.get(obj));
			e.body.put(f1.getName(), (String)f1.get(obj));
		}
		for (Field f2 : fieldSuper){
			f2.setAccessible(true);
			e.head.put(f2.getName(), (String)f2.get(obj));
			}
		String str = buildXML.buildXMLStrByXMLEntity(e);
		return str;
		
	}

  obj中对象属性未使用public修饰,之前未添加f1.setAccessible(true),运行时报错: java.lang.IllegalAccessException: Class union.web.mvc.services.base.InvokeXMLStr can not access a member of class union.web.mvc.services.dataDictionary.addTable.AddTableReqBean with modifiers ""

 

getDeclaredFields()方法无法获得继承属性
getFields()方法无法获得非公共属性
getDeclaredMethods()和getMethods()也同理
posted on 2013-05-07 11:03 逍遥骑士 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/caijing/archive/2013/05/07/3064359.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值