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.

[336 byte] By [roopa_sree] at [2007-9-26 3:07:10]
# 1
To represent int with a Class object, use Integer.TYPEThere are similarly Double.TYPE, Boolean.TYPE etc... for all primitive types.e.g.getMethod("methodName", new Class(){Integer.TYPE})
mattbunch at 2007-6-29 11:10:41 > top of Java-index,Core,Core APIs...
# 2
Sorry, should be new Class[]{Integer.TYPE}
mattbunch at 2007-6-29 11:10:41 > top of Java-index,Core,Core APIs...
# 3
Integer.class is another possibility.
jsalonen at 2007-6-29 11:10:41 > top of Java-index,Core,Core APIs...
# 4
> Integer.class is another possibility. No, no it's not. Sorry about that mistake.
jsalonen at 2007-6-29 11:10:41 > top of Java-index,Core,Core APIs...
# 5
Hi check int.classVinay
psvinayram at 2007-6-29 11:10:41 > top of Java-index,Core,Core APIs...
# 6

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) });

oxbow_lakes at 2007-6-29 11:10:41 > top of Java-index,Core,Core APIs...
# 7

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

psvinayram at 2007-6-29 11:10:41 > top of Java-index,Core,Core APIs...