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

23,741

Solution 1

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)

Solution 2

The doIt method takes two parameters. Consequently you need to pass two parameters, in addition to the method name, to Class#getDeclaredMethod(). The two additional parameters need to be instances of Class, which an Object[] is obviously not. Specifically, those Class instances need to be the same as the types of the parameters that doIt accepts.

Method doIt = A.class.getDeclaredMethod("doIt", int[].class, int[].class);

Solution 3

Shouldn't it be?

Method doIt = A.class.getDeclaredMethod("doIt", int[].class, int[].class);
Share:
23,741
kasavbere
Author by

kasavbere

I LOVE CODE!!!!

Updated on July 09, 2022

Comments

  • kasavbere
    kasavbere almost 2 years

    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.