Java – how to use reflection to call methods with parameters?

This is my lesson:

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

I have another class that tries to modify two arrays using doit I have an error in my code, but I 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,Y});
  }
}

Any help on how to solve mystuff?

If I use getdeclaraedmethod ("doit", new object [] {x, y}); The code is not compiled

If I have getdeclaraedmethod ("doit", null); Then it says nosuchmethodexception

Solution

Your method is declared with two int arrays

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

If you want to find that method, you also need to place its parameter type to prevent finding other methods with the same name but different types

A.class.getDeclaredMethod("doIt",int[].class,int[].class)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>