简体   繁体   中英

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. 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):

Returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object.

You should use Class.getDeclaredFields instead:

Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object. 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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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