Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing List<Integer> with reflection

I have a Java method:

  public void setPri(List<Integer> pri) { this.pri = pri; }

What I want to do is call the method and pass a List. What is the correct approach using reflection?

I was trying the following:

  method = object.getClass().getDeclaredMethod("setPri", List.class);
  method.invoke(null,new Object[] { pri });
like image 528
ogottwald Avatar asked Aug 22 '26 16:08

ogottwald


1 Answers

Your code won't primarily work, because you are not passing an instancs as first parameter:

method.invoke(null,new Object[] { pri });

You need to pass object as first parameter, not null.

This should work:

List<Integer> pri = Arrays.asList(1,2,3,4);
Method method = object.getClass().getDeclaredMethod("setPri", List.class);
method.invoke(object, new Object[] { pri });
like image 162
Stefan Winkler Avatar answered Aug 25 '26 05:08

Stefan Winkler