Google search bar

July 10, 2007

Java reflection: primitive arguments in methods

Suppose that we want to reflexively invoke an instance method for a java object. Further, suppose that one or more of the method arguments is of a primitive type (i.e. int, small, double, ...).

In the Class.getDeclaredMethod(String, Class[]) method, you pass in a string representing the method name and an array of Class objects representing the types of any arguments.

For the following class :

public class Reflector {
public void intMethod(String aString, int anInt) { /* Some Code */}
public void integerMethod(String aString, Integer anInteger) { /* Some Code */}
}

You would get the methods reflectively like so:

. . .
Reflector r = new Reflector();

Method m = r.getClass().getDeclaredMethod("intMethod", Class[] {String.class, Integer.TYPE});
Method m2 = r.getClass().getDeclaredMethod("integerMethod", Class[] {String.class, Integer.class});
. . .


And invoke them thusly:

. . .
m.invoke(r, Object[] {"MyString", Integer.valueOf(100)});
m2.invoke(r, Object[]{"MyString", Integer.valueOf(100)});
. . .


For m.invoke, you wrap the int in the wrapper class since we're passing in an array of Object. Java automatically tries to unwrap it for you.

For an argument that is of primitive types use the following when defining the signature:
byte => Byte.TYPE
short => Short.TYPE
int => Integer.TYPE
long => Long.TYPE
float => Float.TYPE
double => Double.TYPE
boolean => Boolean.TYPE

No comments: