1

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.

Rotav
  • 75
  • 5
  • 1
    I'm not sure if this is possible, but I'm even **more** unsure of why you want to do this? Providing your use-case might allow for an answer that gives a third, better solution – MyStackRunnethOver Nov 28 '18 at 23:23
  • @MyStackRunnethOver I've provided a reason in my edit. – Rotav Nov 28 '18 at 23:45
  • Excellent! Here's a possibly useful link: [How do I test a private...](https://stackoverflow.com/questions/34571/how-do-i-test-a-private-function-or-a-class-that-has-private-methods-fields-or/34658#34658) And the obligatory advice: if you feel you need to test something that's private, you should probably: 1.) make it public, or 2.) remove the *need* to test it (perhaps split it up into accessible functionality you need to test and private you don't) – MyStackRunnethOver Nov 28 '18 at 23:50
  • An `ArrayList` can’t be private. The field containing the reference to it may be. So what you actually want, is to read that private field containing the reference via Reflection. Once you’ve read the field, you can normally access the `ArrayList` through its public interface. – Holger Nov 29 '18 at 16:42

1 Answers1

-1

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.

Rotav
  • 75
  • 5