Biscuit128
Biscuit128

Reputation: 5398

How to modify a List via reflection

I have managed to access a class variable via reflection, and have it stored in a Field variable. I also have the class that field belongs too. How do i transform the Field object in to a List as I want to add to this List using reflection.

The List variable i am accessing via reflection ( and am storing in a Field object) I want to be able to add to it.

Thanks

import java.util.ArrayList;


    public class Test 
    {
        private ArrayList<Integer> aList = new ArrayList<Integer>();

        //some methods...
    }

    Field field = myObject.getClass().getField("aList");;
    field.setAccessible(true);
    //some how add an integer to that list

Upvotes: 2

Views: 3093

Answers (1)

Trevor Freeman
Trevor Freeman

Reputation: 7232

Untested:

ArrayList<Integer> myList = (ArrayList<Integer>) field.get(myObject);
myList.add(5);

I am assuming that the above is what you are trying to do? It is a little bit unclear from your code example.

Also, since the field is private you will need to use getDeclaredField() instead of getField() (as you use in your example).

Upvotes: 7

Related Questions