简体   繁体   English

对实例化对象执行Java反射

[英]Perform java reflection on instantiated objects

I would like to get all the fields of an object that is already instantiated. 我想获取已实例化的对象的所有字段。 from there i like to get the field name and field value and append it to a string 从那里,我喜欢获取字段名称和字段值并将其附加到字符串

public static void main(String[] args) {

TestObject obj = new TestObject();
obj.setName("Toothbrush");
obj.setType("Toiletries");
String result = generateQuery(obj);
} 

public static String generateQuery(TestObject obj){
    String result;
    Field[] lists = obj.getClass().getFields();
    for(Field i : lists){
      try {
        result += i.getName();
        result += i.get(obj);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    return result;  
}

public class TestObject(){
 private String name;
 private String type;

 // getters and setters
}

right now my lists variable is empty. 现在我的列表变量为空。 i have checked various java reflection tutorials and they all instantiate a new object before performing a reflection. 我已经检查了各种Java反射教程,它们都在执行反射之前实例化了一个新对象。 in my case i would like to instantiate an object and set certain variables and then perform reflection. 就我而言,我想实例化一个对象并设置某些变量,然后执行反射。 would request for help on this thank you 会要求帮助的,谢谢

Your fields are private - which is a good thing, but it doesn't play well with Class.getFields (emphasis mine): 您的字段是私有的-很好,但是在Class.getFields (强调我的)上不能很好地发挥作用:

Returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object. 返回一个包含Field对象的数组,该对象反映此Class对象表示的类或接口的所有可访问公共字段。

You should use Class.getDeclaredFields instead: 您应该改用Class.getDeclaredFields

Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object. 返回一个Field对象数组,该数组反映由该Class对象表示的类或接口声明的所有字段。 This includes public, protected, default (package) access, and private fields, but excludes inherited fields. 这包括公共,受保护,默认(程序包)访问和私有字段,但不包括继承的字段。

In order to access the values, you'll need to call field.setAccessible(true) before field.get(obj) . 为了访问这些值,您需要在field.get(obj)之前调用field.setAccessible(true) field.get(obj)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM