Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use reflection to invoke a method with parameters?

Tags:

Here is my class:

public class A{
    private void doIt(int[] X, int[] Y){
       //change the values in X and Y
    }
}

I have another class that is trying to use doIt to modify two arrays. I have an error in my code but can't find it.

public class B{
  public void myStuff(){
    A myA = new A();
    int[] X = {1,2,3,4,5};
    int[] Y = {4,5,6,7,8,9};
    Method doIt = A.class.getDeclaredMethod("doIt",new Object[]{X,Y}); // error
    doIt.setAccessible(true);
    doIt.invoke(myA,new Object[]{X,Y});
  }
}

Any help on how to fix method myStuff?

If I use getDeclaredMethod("doIt",new Object[]{X,Y}); the code does not compile.

If instead I have getDeclaredMethod("doIt",null); then it says NoSuchMethodException.

like image 421
kasavbere Avatar asked Jun 13 '12 19:06

kasavbere


1 Answers

Your method is declared with two int arrays

private void doIt(int[] X, int[] Y)

and if you wan to find that method you also need to put its argument types to prevent finding other method with same name but different types.

A.class.getDeclaredMethod("doIt", int[].class, int[].class)
like image 137
Pshemo Avatar answered Sep 29 '22 13:09

Pshemo