[英]Unknown number of arguments of method in reflection
For example I have a class PartE
such: 例如,我有一个类PartE
如:
public class PartE implements Part
{
protected String method = "getIndex" ;
protected String getIndex ( double dummy,int dummyInt,String dummyString )
{
return "E" ;
}
}
In this code I should invoke a method with unknown number of arguments. 在这段代码中,我应该调用一个参数数量未知的方法。 In this case it is getIndex(double,int,String)
. 在这种情况下,它是getIndex(double,int,String)
。
It can be in this way: 它可以这样:
getIndex()
getIndex(int)
getIndex(boolean,int)
getIndex(int,double,boolean)
So whatever combination of arguments, I have done this but it seems that I am doing error in params[i].newInstance()
because it returns not proper thing for instantiation. 所以无论参数的组合如何,我都已经这样做了,但似乎我在params[i].newInstance()
做错误,因为它返回的不是实例化的东西。 That's why I am taking InstantiationException
. 这就是我接受InstantiationException
的原因。 I got stuck what can I do? 我被困了怎么办?
Class c1 = null;
try {
c1 = Class.forName( "PartE" );
} catch (ClassNotFoundException ex) {}
Object obj = null;
obj = c1.newInstance();
Method [] methods = c1.getDeclaredMethods();
for(Method m:methods)
{
m.setAccessible(true);
Class<?>[] params = m.getParameterTypes();
Object[] paramObjects = new Object[params.length];
for (int i = 0; i < params.length; i++)
{
paramObjects[i] = params[i].newInstance();
}
try {
System.out.println(m.invoke(obj, paramObjects));
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {}
You need to handle the possibility that the class you need doesn't support a no-params constructor, since newInstance
requires one but neither Integer
nor Double
has one. 你需要处理你需要的类不支持no-params构造函数的可能性,因为newInstance
需要一个但是Integer
和Double
都没有。 That means you'll need to add branching within your loop over the parameter types, to at least handle Integer
and Double
. 这意味着您需要在循环中添加参数类型的分支,以至少处理Integer
和Double
。 Presumably the assignment tells you what values you should use (or that it doesn't matter what values you use) for those arguments, since you can't pass null
(you'll get an unboxing error if you use null
since the method expects int
and double
, not Integer
and Double
) and they don't have a no-params constructor. 大概这个赋值告诉你应该使用哪些值(或者你使用的值无关紧要),因为你不能传递null
(如果你使用null
你会得到一个解包错误,因为方法需要int
和double
,不是Integer
和Double
)并且它们没有no-params构造函数。
This answer is intentionally given as prose rather than code because the point of the assignment, presumably, is to learn to write that code. 这个答案是作为散文而不是代码故意给出的,因为分配的重点可能是学会编写代码。 :-) :-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.