For example I have a class PartE such:
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).
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. That's why I am taking 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) {}
Aucun commentaire:
Enregistrer un commentaire