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?
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.
Method methods = ArrayList.class.getMethod("get", int.class);
您不需要在.class之后再次调用getClass()方法,因为当您在类名之后编写.class时,它引用了表示给定类的Class对象。
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.