Java反射-传入ArrayList作为要调用的方法的参数

想要将arraylist类型的参数传递给我要调用的方法。

我遇到一些语法错误,所以我想知道这是什么问题。

方案1:

// i have a class called AW

class AW{}

// i would like to pass it an ArrayList of AW to a method I am invoking

// But i can AW is not a variable

Method onLoaded = SomeClass.class.getMethod("someMethod", ArrayList<AW>.class );

Method onLoaded = SomeClass.class.getMethod("someMethod", new Class[]{ArrayList<AnswerWrapper>.class} );

方案2(不相同,但相似):

// I am passing it as a variable to GSON, same syntax error

ArrayList<AW> answers = gson.fromJson(json.toString(), ArrayList<AW>.class);

回答:

您的(主要)错误是AWgetMethod()参数中传递了不必要的泛型类型。我试图编写一个与您的代码相似但可以正常工作的简单代码。希望它可以某种方式回答您的问题:

import java.util.ArrayList;

import java.lang.reflect.Method;

public class ReflectionTest {

public static void main(String[] args) {

try {

Method onLoaded = SomeClass.class.getMethod("someMethod", ArrayList.class );

Method onLoaded2 = SomeClass.class.getMethod("someMethod", new Class[]{ArrayList.class} );

SomeClass someClass = new SomeClass();

ArrayList<AW> list = new ArrayList<AW>();

list.add(new AW());

list.add(new AW());

onLoaded.invoke(someClass, list); // List size : 2

list.add(new AW());

onLoaded2.invoke(someClass, list); // List size : 3

} catch (Exception ex) {

ex.printStackTrace();

}

}

}

class AW{}

class SomeClass{

public void someMethod(ArrayList<AW> list) {

int size = (list != null) ? list.size() : 0;

System.out.println("List size : " + size);

}

}

以上是 Java反射-传入ArrayList作为要调用的方法的参数 的全部内容, 来源链接: utcz.com/qa/413255.html

回到顶部