Question

Why can't I get the "get" method of an ArrayList and invoke it?

I am using reflection to modify within my nested classes. One of my classes has a list of classes so I wanted to be able to use the same logic to get and invoke the get method.

simplified, the line that fails is

ArrayList.class.getClass().getMethod("get")

and it fails, giving me a NoSuchMethodException.

I understand that I could use aList.get() but that's not the point, I need to use reflection since this is in a deeply nested class.

TL;DR How can I get the "get" method of an array list?

Was it helpful?

Solution

Note that Class#getMethod() has two parameters: a String and an vararg of Class objects. The former is

the list of parameters

that the method declares.

You need to use

ArrayList.class.getMethod("get", int.class);

since the ArrayList#get(int) method has an int parameter.


I initially missed the whole

ArrayList.class.getClass().getMethod("get")
          ^     ^ 
          |     |----------------------------- gets Class<Class>
          |----------------------------------- gets Class<ArrayList>

The .class already gets the Class instance for ArrayList. Calling getClass on that will return the Class instance for class Class. You don't want that.

OTHER TIPS

Method methods = ArrayList.class.getMethod("get", int.class);

You do not need to call getClass() method again after .class because when you write .class after a class name, it references the Class object that represents the given class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top