Java对不同参数编号的反射
是否可以将不同数量的参数传递给动态反射方法?
我有N类,例如,
class A { method_A(T arg1, S arg2){}}
class B { method_B(T arg1){}}
class C //... and so on
我尝试构建能够在任何类中调用任何方法的函数,
main(){
Object[] args = {"arg1", "arg2"};
foo(new A(), "method_A", args);
}
foo(Object obj, String objectiveMethod, Object[] params){
Method[] allMethods = obj.getClass().getDeclaredMethods();
for(Method method: allMethods){
//find the objective method, irrelevant to the question
if(objectiveMethod.equals(method.getName())){
method.invoke(obj, params); // Here throws IllegalArgumentException: wrong number of arguments
}
}
}
我可以轻松地检索参数Method.getParameterCount()
,但是我无法弄清楚如何动态传递从对象[] args;
检索的参数数。
我以为methodAccessor.invoke(object obj,object [] args)
可以处理(因为对象[] args),但它不起作用,但
IllegalArgumentException: wrong number of arguments
您可以帮助我找出任何方法实现这一目标?还是不可能?
- 编辑 -
f(){
A aObj = new A(); C cObj = new C();
Object[] args = {"arg1", "arg2"};
Object[] argsC = {"arg1", 2, new B()};
aObj.method_A(args[0], args[1]); // works fine
...
/* It doesn't matter which type of object they are, they still have known of it's type without casting*/
method.invoke(aObj, args[0], args[1]); // works fine
method.invoke(aObj, args); // doesn't work, wrong number of args.
methodC.invoke(cObj, args...?);// 3 args dynamically
}
Is it possible to pass different number of arguments to a dynamic reflection method??
I have N classes, for instance
class A { method_A(T arg1, S arg2){}}
class B { method_B(T arg1){}}
class C //... and so on
I try to build a function able to invoke any method in any class
main(){
Object[] args = {"arg1", "arg2"};
foo(new A(), "method_A", args);
}
foo(Object obj, String objectiveMethod, Object[] params){
Method[] allMethods = obj.getClass().getDeclaredMethods();
for(Method method: allMethods){
//find the objective method, irrelevant to the question
if(objectiveMethod.equals(method.getName())){
method.invoke(obj, params); // Here throws IllegalArgumentException: wrong number of arguments
}
}
}
I can easily retrieve the amount of arguments Method.getParameterCount()
, but i can't figure out how to dynamically pass N number of arguments retrieved from Object[] args;
.
I thought that MethodAccessor.invoke(Object obj, Object[] args)
could handle this (because of Object[] args) but it doesn't work and throws
IllegalArgumentException: wrong number of arguments
Could you help me figure out any way to achieve that? Or it's impossible?
--edit--
f(){
A aObj = new A(); C cObj = new C();
Object[] args = {"arg1", "arg2"};
Object[] argsC = {"arg1", 2, new B()};
aObj.method_A(args[0], args[1]); // works fine
...
/* It doesn't matter which type of object they are, they still have known of it's type without casting*/
method.invoke(aObj, args[0], args[1]); // works fine
method.invoke(aObj, args); // doesn't work, wrong number of args.
methodC.invoke(cObj, args...?);// 3 args dynamically
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论