反射初试

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

public String callXMLHandler(Object obj) throws IllegalArgumentException, IllegalAccessException{
		Class clazz = (Class)obj.getClass();
		Class clazzSuper = (Class) 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()也同理

你可能感兴趣的:(反射初试)