invoking method thru reflection
I have got a method which takes in a primitive datatype (eg. int) as its argument. One of the parameters of getMethod() in the class Class is Class[] representing the various args of the method to be invoked. How do I represent the primitive data type as part of this Class[]?
Your reply will be greatly appreciated.
It is worth mentioning that when you invoke the method, you cannot send your int thru as a parameter, you must send an Integer instead...
int intValue = 4;
Method m = obj.getClass().getMethod("myMethod", new Class[] { Integer.TYPE }); //or int.class
m.invoke(obj, new Object[]{ new Integer(intValue) });
import java.lang.reflect.*;
public class TT {
public static void loadClass(String className,String methodName,String arg)
{
Classl_class;
java.lang.ObjectreturnValue=new Object();
try{
Class[] parameterTypes = new Class[] { int.class };
l_class=Class.forName(className);
java.lang.Object o = l_class.newInstance();
Method method =l_class.getMethod(methodName, parameterTypes);
java.lang.Object arguments[] = new java.lang.Object[1];
arguments[0] =new Integer(arg) ;
returnValue=method.invoke(o, arguments);
if( returnValue instanceof Integer ){
System.out.println("Int value = "+((Integer)returnValue).intValue() );
}
else{
System.out.println("Int value false");
}
}
catch(NoSuchMethodException nsme){}
catch(IllegalArgumentException iae){}
catch(InvocationTargetException ite){}
catch(Exception e){ }
return ;
}
public static void main(String[] args) throws Exception
{
loadClass( args[0] , args[1], args[2] );
}
}
/// Example.java
public class Example
{
public int get(int i){
return i;
}
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
psvinayram@yahoo.com