Javareflection – 传入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.class ); Method onLoaded = SomeClass.class.getMethod("someMethod", new Class[]{ArrayList.class} ); 

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

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

您的(主要)错误是在getMethod()参数中传递不必要的generics类型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 list = new ArrayList(); 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 list) { int size = (list != null) ? list.size() : 0; System.out.println("List size : " + size); } } 

类文字没有以这种方式参数化,但幸运的是你完全不需要它。 由于擦除,只有一个方法有一个ArrayList作为参数(你不能在generics上重载)所以你可以使用ArrayList.class并获得正确的方法。

对于GSON,他们引入了一个TypeToken类来处理类文字不表达generics的事实。