例如,我有一个类PartE
,如:
public class PartE implements Part
{
protected String method = "getIndex" ;
protected String getIndex ( double dummy,int dummyInt,String dummyString )
{
return "E" ;
}
}
在这段代码中,我应该调用一个参数数量未知的方法。在这种情况下,它是getIndex(double,int,String)
。
可以这样:
getIndex()
getIndex(int)
getIndex(boolean,int)
getIndex(int,double,boolean)
所以无论参数组合如何,我都已经这样做了,但似乎我在params[i].newInstance()
中做错了,因为它返回的实例化不合适。这就是我采取InstantiationException
的原因。我遇到了什么困难?
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) {}
答案 0 :(得分:0)