Java反射注入数组或者可变参数


下面两种写法,语法上看不出错误,算是细节和易错点吧。

invock方法的第二个参数是可变数组,这个参数可以传也可以不传,这个参数可以认为是一个Object类型的数组,如果直接给第二个参数传递一个数组,那么此数组将替换Object数组。

假定:我们有一个数组:String arr=new String[]{"a"},希望将这arr个数组注入给我们的方法,

1、如果我们传递的是一个普通参数,比如字符串“a”,执行invock(obj,“a”),此时,invock()方法第二个参数值实际上是new Object[]{"a"};

2、同理,如果我们传递的是一个数组arr,invock()方法第二个参数应该是new Object[]{arr};

3、但是,如果执行invoce(obj,arr),此时的第二个参数实际上是new String[]{"a"},因为arr数组直接替换掉了Object数组;

4、显然,参数传递的不对,方法的执行结果不是我们想要的,正确的做法是执行invoce(obj,new Object[]{arr})

public class UserTest { List<UserTest> list = new ArrayList<>(); public void testPrint(String... params){ for (String string : params) { System.out.println(string); } } public static void main(String[] args) { try { UserTest userTest=new UserTest(); Class<?> clazz=userTest.getClass(); Method[] methods=clazz.getMethods(); for (Method method : methods) { if(!"testPrint".equals(method.getName())) continue; System.out.println(method.getName()); String[] arr=new String[]{"aaaa",null,"bbbb"}; //正确
        method.invoke(userTest,new Object[]{arr}); } } catch (Exception e) { e.printStackTrace(); } } @Test public void test() { try { UserTest userTest=new UserTest(); Class<?> clazz=userTest.getClass(); Method[] methods=clazz.getMethods(); for (Method method : methods) { if(!"testPrint".equals(method.getName())) continue; System.out.println(method.getName()); String[] arr=new String[]{"aaaa",null,"bbbb"}; //错误
 method.invoke(userTest,arr); } } catch (Exception e) { e.printStackTrace(); } } }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM