简体   繁体   中英

How to get last value from an ArrayList using reflection?

I simply want to get the last value in an ArrayList using reflection. Typically this is achieved by doing:

String s = ArrayList.get(ArrayList.size()-1);

I've tried doing:

String s = Object.get(ClassInstance, Object.get(ClassInstance, ArrayList.size()-1));

Obviously this isn't the correct syntax. What would the correct syntax be to achieve this?

EDIT:

The reason for trying to do this is because I am unit testing my code and the ArrayList located inside the class I am testing is private. One of my boolean methods takes a parameter and I wanted to test it using the last value in the ArrayList (I don't know the value as it is randomly generated, but the value should always return true). Any solutions for this problem are much appreciated.

Finally managed to figure this out for myself. Posting the code for anyone in the future that might need it:

MyClass myClass = new MyClass();
Field list = MyClass.class.getDeclaredField("listName");
list.setAccessible(true);
List<String> l = (ArrayList) list.get(myClass);
String s = l.get(l.size()-1);

The method this is contained in needs to throw a NoSuchFieldException and IllegalAccessException in order for it to work.

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