一、异常描述
在获取对象内部类Student属性属性obj.getClass().getDeclaredFields()的时,报Exception in thread "main" java.lang.IllegalAccessException: Class test.ObjectReflectUtils can not access a member of class test.ObjectReflectUtils$Student with modifiers "private"异常,详情日志如下
Exception in thread "main" java.lang.IllegalAccessException: Class test.ObjectReflectUtils can not access a member of class test.ObjectReflectUtils$Student with modifiers "private"@b@ at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:65)@b@ at java.lang.reflect.Field.doSecurityCheck(Field.java:960)@b@ at java.lang.reflect.Field.getFieldAccessor(Field.java:896)@b@ at java.lang.reflect.Field.get(Field.java:358)@b@ at test.ObjectReflectUtils.getFieldsMap(ObjectReflectUtils.java:78)@b@ at test.ObjectReflectUtils.main(ObjectReflectUtils.java:250)
二、解决方法
1.对象工具类通过内部类Student属性转换getFieldsMap方法处理(完整代码示例参见其他文章页),代码如下
public class ObjectReflectUtils { @b@ @b@ public static Map getFieldsMap(Object obj) throws Exception{@b@ Field[] fields=obj.getClass().getDeclaredFields();@b@ Map fieldMap=new HashMap();@b@ for(Field f:fields){ @b@ fieldMap.put(f.getName(),f.get(obj));@b@ }@b@ return fieldMap;@b@ }@b@ ..@b@ public static class Student{@b@ @b@ private String name;@b@ private String classId;@b@ @b@ public Student() {@b@ super();@b@ }@b@@b@ public Student(String name, String classId) {@b@ super();@b@ this.name = name;@b@ this.classId = classId;@b@ }@b@ @b@ public String getName() {@b@ return name;@b@ }@b@ public void setName(String name) {@b@ this.name = name;@b@ }@b@ public String getClassId() {@b@ return classId;@b@ }@b@ public void setClassId(String classId) {@b@ this.classId = classId;@b@ }@b@ }@b@}
2. 因为对象内部类都是私有方法,因此增加类的f.setAccessible(true);可访问属性处理,如下
public class ObjectReflectUtils { @b@ @b@ public static Map getFieldsMap(Object obj) throws Exception{@b@ Field[] fields=obj.getClass().getDeclaredFields();@b@ Map fieldMap=new HashMap();@b@ for(Field f:fields){ @b@ @b@ boolean accessible = f.isAccessible();@b@ if (!accessible) {@b@ f.setAccessible(true);@b@ }@b@ @b@ fieldMap.put(f.getName(),f.get(obj));@b@ @b@ }@b@ return fieldMap;@b@ }@b@ ..@b@ @b@}