gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 02:12:55 26 4
gpt4 key购买 nike

想将 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} );

场景二(不一样,但很相似):

// I am passing it as a variable to GSON, same syntax error
ArrayList<AW> answers = gson.fromJson(json.toString(), ArrayList<AW>.class);

最佳答案

您的(主要)错误是在您的 getMethod() 参数中传递了不必要的通用类型 AW。我试着写了一个简单的代码,类似于你的代码,但可以工作。希望它能以某种方式回答(一些)你的问题:

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 作为要调用的方法的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13876300/

26 4 0