zoukankan      html  css  js  c++  java
  • 反射初试

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

    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()也同理
  • 相关阅读:
    基于Python的接口测试框架
    接口自动化之Postman+Newman
    UIAutomator定位Android控件的方法
    HTTP接口功能自动化测试入门
    前端基础:HTML标签(上)
    Python 面向对象进阶
    Python 断言和异常
    Linux 文件上传Linux服务器
    Python 运算符
    Python 基本数据类型
  • 原文地址:https://www.cnblogs.com/caijing/p/3064359.html
Copyright © 2011-2022 走看看