Wednesday, July 16, 2008

Java reflection tip of the day

Suppose you want to call a private method of a class called FourGablesGuy. Suppose further that the private method of this class has primitive type arguments.

public FourGablesGuy {
private String privateMethod(int intParm, boolean boolParam)
{
return "four gables guy";
}
}



Using reflection you can do it, but it was a little tricky for me.


...
FourGablesGuy myFourGablesGuy = new FourGablesGuy();
Object[] args = new Object[]{ new Integer(921), new Boolean(true)};
Class[] params = new Class[] { Integer.TYPE, Boolean.TYPE };
String result;
try {
Method privateMethod = myFourGablesGuy.getClass().getDeclaredMethod(
"privateMethod", params);
privateMethod.setAccessible(true);
result = (String) privateMethod.invoke(myFourGablesGuy, args);
} catch (NoSuchMethodException nsme) {
//do stuff
throw nsme;
} catch (InvocationTargetException ite) {
//do stuff
throw ite;
} catch (IllegalAccessException iae) {
//do stuff
throw iae;
}
// at this point the result String should have the value of the private method call
...


Getting the Class object for the primitive types was one issue, it is not java.lang.Integer! Also, knowing that an Object Array of a java.lang.Integer object and java.lang.Boolean object will be acceptable arguments to a Method defined with primitive params was the other big logic hurdle.
Hope this helps someone, maybe some Java professor needs a tough bonus reflection question. Or maybe this is all just obvious to the entire Java community and I am the last one to figure it out.
So if you are getting NoSuchMethodException and the method is using primitives, it is probably because you are not using Integer.TYPE for the Class Array of parameters and are using Integer.class instead.

No comments:

About Me

My photo
Lead Java Developer Husband and Father

Tags