sriram
sriram

Reputation: 9032

How to get the reference to the instance variable?

I have the following code to get the value of my class instance variable.

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

Lets say for class A, which has type ArrayList. Looks like:

class A
{
   private ArrayList list;
}

Now I want to get the reference to this type list. Is it possible?

So that once I get the reference all the methods available in the ArrayList should be accessible.

How to do it?

Upvotes: 1

Views: 110

Answers (5)

Pshemo
Pshemo

Reputation: 124225

  1. If you want to get all fields declared in instance class (not only public ones) you need to use getDeclaredFields() instead of getFields().

  2. Also if you want to have access to value of private fields you need to set its accessibility to true with field.setAccessible(true).

Upvotes: 0

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

You can get the value from the Field instance by:

  1. Setting the field as accessible with AccessibleObject#setAccessible(boolean b) method (which is implemented in the Field class).
  2. Fetching its value via the Field#get(Object obj) method.

For example:

for (Field f : fields) {
    f.setAccessible(true);
    ArrayList value = (ArrayList) f.get(objClass);
}

Upvotes: 1

Slimu
Slimu

Reputation: 2371

Yes, you can do that. For non public fields you must use the field.getDeclaredField() method. If you wish to set or read a value for that field, you must use field.setAccessible(true). Be careful for NPE when using value.toString() for null fields.

public static void printFields(Object obj) throws Exception {
    Class<?> objClass = obj.getClass();

    Field[] fields = objClass.getDeclaredFields();
    for(Field field : fields) {
        field.setAccessible(true);
        String name = field.getName();
        Object value = field.get(obj);

        System.out.println(name + ": " + value);
    }
}

Upvotes: 0

peter.petrov
peter.petrov

Reputation: 39457

Try this.

public ArrayList getField(A obj) throws Exception{
    Class c = obj.getClass();
    Field f = c.getDeclaredField("list");
    f.setAccessible(true);
    ArrayList lst = (ArrayList)f.get(obj);
    return lst;
}

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234685

You can use field.setAccessible(true); to circumvent encapsulation. This doesn't necessarily always work: a SecurityException may be thrown.

It's far better (if you own the class), to set the member public and be done with it:

class A
{
   public ArrayList list;
}

At least then your usage pattern is expected.

Once you have obtained the list then any public methods and fields on that list will be available to you.

Upvotes: 1

Related Questions