Java 反射 - 传入一个 ArrayList 作为要调用的方法的参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13876300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Reflection - Passing in a ArrayList as argument for the method to be invoked
提问by ming yeow
would like to pass an argument of arraylist type to a method i am going to invoke.
想将 arraylist 类型的参数传递给我要调用的方法。
I am hitting some syntax errors, so I was wondering what was wrong with what this.
我遇到了一些语法错误,所以我想知道这有什么问题。
Scenario 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} );
Scenario 2 (not the same, but similar):
场景2(不一样,但相似):
// I am passing it as a variable to GSON, same syntax error
ArrayList<AW> answers = gson.fromJson(json.toString(), ArrayList<AW>.class);
回答by Yohanes Gultom
Your (main) mistake is passing unnecessary generic type AW
in your getMethod()
arguments. I tried to write a simple code that similar to yours but working. Hopefully it may answers (some) of your question somehow :
您的(主要)错误是AW
在您的getMethod()
参数中传递了不必要的泛型类型。我试图编写一个与您类似但有效的简单代码。希望它可以以某种方式回答您的(某些)问题:
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);
}
}
回答by gk5885
Class literals aren't parameterized in that way, but luckily you don't need it at all. Due to erasure, there will only be one method that has an ArrayList as a parameter (you can't overload on the generics) so you can just use ArrayList.class and get the right method.
类文字不是以这种方式参数化的,但幸运的是您根本不需要它。由于擦除,只有一种方法将 ArrayList 作为参数(您不能重载泛型),因此您可以只使用 ArrayList.class 并获得正确的方法。
For GSON, they introduce a TypeToken
class to deal with the fact that class literals don't express generics.
对于 GSON,他们引入了一个TypeToken
类来处理类文字不表达泛型的事实。