简体   繁体   English

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

[英]Passing List as Parameter to java.lang.reflect.Method

I have a method which looks like this;我有一个看起来像这样的方法;

public void update(List<Object> obj);

I want to be able to use java.lang.reflect.Method to invoke the method.我希望能够使用java.lang.reflect.Method来调用该方法。 Do anyone know how to go about doing this?有谁知道如何做到这一点?

Use the Class class to get the method:使用Class class获取方法:

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

and then invoke the method:然后调用方法:

method.invoke(theObject, new ArrayList<Object>());

Generics are erased at runtime. Generics 在运行时被擦除。 They're a compile-time thing.它们是编译时的东西。 You may thus use List.class to refer to a List<Object> .因此,您可以使用List.class来引用List<Object>

yes, you can do是的,你可以

myObject.getClass()
    .getMethod("update", List.class)
    .invoke(myObject, myListOfObject);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM