将List作为参数传递给java.lang.reflect.Method

Bit*_*map 1 java generics

我有一个看起来像这样的方法;

public void update(List<Object> obj);
Run Code Online (Sandbox Code Playgroud)

我希望能够使用java.lang.reflect.Method来调用该方法.有谁知道怎么做这个?

JB *_*zet 5

使用Class该类获取方法:

Class<?> clazz = theObject.getClass();
Method method = clazz.getMethod("update", List.class);
Run Code Online (Sandbox Code Playgroud)

然后调用方法:

method.invoke(theObject, new ArrayList<Object>());
Run Code Online (Sandbox Code Playgroud)

泛型在运行时被擦除.它们是编译时间的东西.因此你可以List.class用来指代a List<Object>.