想将 arraylist 类型的参数传递给我要调用的方法。
我遇到了一些语法错误,所以我想知道这有什么问题。
场景一:
// 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} );
Run Code Online (Sandbox Code Playgroud)
场景2(不一样,但相似):
// I am passing it as a variable to GSON, same syntax error
ArrayList<AW> answers = gson.fromJson(json.toString(), ArrayList<AW>.class);
Run Code Online (Sandbox Code Playgroud)
您的(主要)错误是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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11147 次 |
| 最近记录: |