1

为什么我不能获取 ArrayList 的“get”方法并调用它?

我正在使用反射在我的嵌套类中进行修改。我的一个类有一个类列表,所以我希望能够使用相同的逻辑来获取和调用 get 方法。

简化,失败的行是

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

它失败了,给了我一个 NoSuchMethodException。

我知道我可以使用 aList.get() 但这不是重点,我需要使用反射,因为这是一个深度嵌套的类。

TL;DR 如何获取数组列表的“get”方法?

4

2 回答 2

4

请注意,它Class#getMethod()有两个参数:对象的 aString和可变参数Class。前者是

参数列表

该方法声明的。

你需要使用

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

因为该ArrayList#get(int)方法有一个int参数。


我最初错过了整个

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

.class已经Class获得ArrayList. _ 调用getClass它将返回Classclass 的实例Class。你不想要那个。

于 2013-09-30T17:35:55.140 回答
2
Method methods = ArrayList.class.getMethod("get", int.class);

您不需要在 .class 之后再次调用 getClass() 方法,因为当您在类名之后编写 .class 时,它引用了表示给定类的 Class 对象。

于 2013-09-30T17:49:24.057 回答