java反射传入参数是list<string>,具体该怎么写?

Method writefile = basiclib.getDeclaredMethod("writeFile", new Class[] {List<String>.class,String.class});

            List<String> lines2 = (List<String>) readfile.invoke(null, new Object[] {filepath2});
            

            
            lines2 = (List<String>)
                    _methods[i].invoke(_actionxp1,
                            new Object[] {lines2});
                            
                            

这么写好像不太对,网上一搜索list全跑出来获取泛型数据类型,这尼玛的真坑。

阅读 10.6k
1 个回答

List.class即可,泛型参数在编译后会被擦除掉,无论List里面是String还是什么别的东西都不会影响获取到那个method,在invoke的时候传的参数对不上的话才会产生异常

//Test.java
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Test {
    public static void main(String[] args) throws InterruptedException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        final Class<Tmp> tmpClass = Tmp.class;
        final Method printStrings = tmpClass.getDeclaredMethod("printStrings", List.class);
        List<String> strings = Stream.iterate(1, t -> t + 1).limit(10).map(Object::toString).collect(Collectors.toList());
        List<Integer> integers = Stream.iterate(1, t -> t + 1).limit(10).collect(Collectors.toList());
        printStrings.invoke(new Tmp(), strings);//正常执行,打出1~10
        printStrings.invoke(new Tmp(), integers);//产生异常
    }
}

class Tmp {
    void printStrings(List<String> strings) {
        strings.forEach(System.out::println);
    }
}

输出

1
2
3
4
5
6
7
8
9
10
Exception in thread "main" Disconnected from the target VM, address: '127.0.0.1:56752', transport: 'socket'
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at Test.main(Test.java:17)
Caused by: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
    at java.util.ArrayList.forEach(ArrayList.java:1249)
    at Tmp.printStrings(Test.java:23)
    ... 5 more

Process finished with exit code 1
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏