获取类实例变量并使用reflection打印它们的值
我有一个带有getter和setter的2个POJO类,现在我正在尝试获取该类的所有类实例变量。
我知道我们可以用reflection怎么做?
这是我的POJO类,它将扩展我的reflection类。
class Details{ private int age; private String name; }
反思类是这样的:
class Reflection{ public String toString(){ return all the fields of that class }
你可以这样做:
public void printFields(Object obj) throws Exception { Class> objClass = obj.getClass(); Field[] fields = objClass.getFields(); for(Field field : fields) { String name = field.getName(); Object value = field.get(obj); System.out.println(name + ": " + value.toString()); } }
这只会打印公共字段,打印私有字段递归使用class.getDeclaredFields。
或者如果你要扩展课程:
public String toString() { try { StringBuffer sb = new StringBuffer(); Class> objClass = this.getClass(); Field[] fields = objClass.getFields(); for(Field field : fields) { String name = field.getName(); Object value = field.get(this); sb.append(name + ": " + value.toString() + "\n"); } return sb.toString(); } catch(Exception e) { e.printStackTrace(); return null; } }
上面提到的解决方案代码或答案有一个问题。 要访问私有变量的值,必须将其访问类型设置为true
Field[] fields = objClass.getDeclaredFields(); for (Field field : fields) { NotNull notNull = field.getAnnotation(NotNull.class); field.setAccessible(true); }
否则会抛出java.lang.IllegalAccessException
。 Class Reflection无法使用修饰符“private”访问类Details的成员
ClassLoader classLoader = Main.class.getClassLoader(); try { Class cls = classLoader.loadClass("com.example.Example"); Object clsObject = cls.newInstance(); Field[] fields = cls.getFields(); for (Field field : fields) { String name = field.getName(); Object value = field.get(clsObject); System.out.println("Name : "+name+" Value : "+value); } System.out.println(cls.getName()); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); }
在上面的代码中再添加一行。 如果要访问该类的私有属性,请使用以下行
field.setAccessible(真);