18

I have a 2 POJO classes with getters and setters,now i am trying to get all the class instance variables of that class.

I got to know that we can use reflection how to do it?

This is my POJO Class which will extend my reflection class.

class Details{

private int age;
private String name;

}

Reflection class is like this:

class Reflection{

public String toString(){

return all the fields of that class
}
Andremoniy
  • 34,031
  • 20
  • 135
  • 241
Goofy
  • 6,098
  • 17
  • 90
  • 156

4 Answers4

41

You could do something like this:

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());
    }
}

This would only print the public fields, to print private fields use class.getDeclaredFields recursively.

Or if you would extend the class:

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;
    }
}
Emiel
  • 473
  • 6
  • 7
  • ok but can i override toString method and do it in the same way? which will return me all the fields? – Goofy Feb 27 '13 at 13:00
  • Sure, you would have to append the name/value to a string instead of printing it out and you would also need a reference to an instance of the Details class in your Reflection class. – Emiel Feb 27 '13 at 13:05
  • i wil tell you what i am trying to do if i extend the class which has toString method in it and print all the field names... but the prob is toString is a buit in method and cannot pass any parameters to that – Goofy Feb 27 '13 at 13:09
  • So, Details extends Reflection? If it does, substitute obj with this. – Emiel Feb 27 '13 at 13:10
  • @Mast3rPlan I couldn't properly understand this part: Object value = field.get(this); What is this supposed to be? What kind of Object? I tried many times to create a new object but I couldn't. Also, how could I access the value of a certain field and use it in a conditional statement? – Geosphere Jun 09 '16 at 22:03
  • mark the field as accessible using `field.setAccessible(true); ` before `Object value = field.get(obj);` – Arpit Aggarwal Aug 28 '16 at 07:02
3

Adding one more line to the above code. If you want to access the private properties of the class use below line

field.setAccessible(true);

Prasad
  • 1,089
  • 13
  • 21
2
    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();
    }
1

The resolution code or answer which mentioned above has one issue. To access the value of a private varible their access type must be set to true

Field[] fields = objClass.getDeclaredFields();
for (Field field : fields) {
    NotNull notNull = field.getAnnotation(NotNull.class);
    field.setAccessible(true);
}

else it will throw java.lang.IllegalAccessException. Class Reflection can not access a member of class Details with modifiers "private"

GabrielOshiro
  • 7,986
  • 4
  • 45
  • 57
Prasad
  • 1,089
  • 13
  • 21