java 如何使用反射调用带参数的方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11022208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I use reflection to invoke a method with parameters?
提问by kasavbere
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.
我有另一个类试图doIt
用来修改两个数组。我的代码中有错误,但找不到。
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
?
有关如何修复方法的任何帮助myStuff
?
If I use getDeclaredMethod("doIt",new Object[]{X,Y});
the code does not compile.
如果我使用getDeclaredMethod("doIt",new Object[]{X,Y});
的代码不编译。
If instead I have getDeclaredMethod("doIt",null);
then it says NoSuchMethodException
.
如果相反,我有getDeclaredMethod("doIt",null);
那么它说NoSuchMethodException
。
回答by Pshemo
Your method is declared with two int arrays
您的方法是用两个 int 数组声明的
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)
回答by Matt Ball
The doIt
method takes twoparameters. Consequently you need to pass twoparameters, 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.
该doIt
方法有两个参数。因此,除了方法名称之外,您还需要将两个参数传递给Class#getDeclaredMethod()
. 这两个附加参数需要是 的实例Class
,而 anObject[]
显然不是。具体来说,这些Class
实例需要与doIt
接受的参数类型相同。
Method doIt = A.class.getDeclaredMethod("doIt", int[].class, int[].class);
回答by Edwin Dalorzo
Shouldn't it be?
不应该吗?
Method doIt = A.class.getDeclaredMethod("doIt", int[].class, int[].class);