如何使用ReflectionAPI在地图上调用“放置”方法

Map map = new HashMap();
Method[] methods = map.getclass().getMethods();
Method method = map.getclass().getMethod("put");

我在方法数组中看到了方法“ put”,但是我收到了getMethod(“ put”)的NoSuchMethodException。

为什么会这样,我如何访问put方法?我需要调用它。

jsxzxuhu 回答:如何使用ReflectionAPI在地图上调用“放置”方法

要使用getMethod,不仅必须提供要获取的方法的名称,还必须提供其参数类型作为Class<?>对象。由于您没有传递任何参数类型,因此它正在寻找一个名为put的方法,该方法不接受任何参数,但是不存在这样的方法。 HashMap.put方法有两个参数。

这些作品:

Method m1 = String.class.getMethod("length");
Method m2 = List.class.getMethod("get",int.class);
Method m3 = HashMap.class.getMethod("put",Object.class,Object.class);

String.length方法不带参数,因此Class<?>中不需要getMethod参数。另一方面,List.get方法采用一个int参数,因此我们需要将int.class作为参数传递给getMethod

请注意,即使HashMap<K,V>是泛型类,参数类型也都是Object,因为KV都不是实类。它们是类型参数,其上限为Object。因此,getMethod需要使用两个Object.class参数来调用。

本文链接:https://www.f2er.com/3155549.html

大家都在问