Search code examples
javareflectiondata-retrieval

How do I retrieved field value from other java class?


Class<?> c = Class.forName("other");
Field[] field = c.getDeclaredFields();
System.out.println("name of field: "+fieldA[0].getName());

I can retrieve field name from other .java file but not the value.

Example:

<other.java file>   public int namefield = 5;

from my main.java execute file

I would like to retrieved the field name and the value.

display: name of field: namefield  value: 5 

Solution

  • Assume your class, which you want to inspect is:

    public class ClassA {
        private String someString = "foo";
        public String anotherString = "bar";
    }
    

    The call of ClassA.class.getDeclaredFields() will return an array with two elements, but as one of the fields is private it cannot be accessed directly. To be able to you have to make it accessible first:

    ClassA objectOfTypeClassA = ...
    for (Field f : objectOfTypeClassA.getClass().getDeclaredFields()) {
      f.setAccessible(true);
      System.out.println("Value of "+f.getName()+" in class "+ClassA.class.getName()+" is "+f.get(objectOfTypeClassA));
    }
    

    To retrieve the value of a non static field you need to pass along the object instance on which the field value is defined.