Reflection on primitive types and their wrapper classes in Java SE 6

Posted on January 8, 2008

1


Since Java 5, we’ve got auto-boxing for primitive data types, remember this only works for primitive types not primitive arrays since arrays are considered as objects.

Now, the question comes: how we can invoke a method using reflection when some of parameters are in primitive types? Basically, before you can call a method, you need to get reference to that Method object. Normally what I do is to use getMethod or getDeclaredMethod with the name of method and parameter types in Class array. In this case, int.class is different from Integer.class. Therefore if a method has int input parameter, you can’t get this method by Integer.class as parameter type.

The strange thing is if you can get the reference of that method (by listing all method and find the method by name possibly), then you can call that method with Integer argument. Java 6 auto-boxing works in this case.

For primitive arrays, they are all considered as objects, therefore Integer[] is completely different from int[]. In this case, you can’t use Java reflection to find the method and you can’t use Java reflection to call that method. Remember arrays are different from primitive types.

OK, finally, the most interesting thing is that you can use MethodUtil in BeanUtil framework to call a method when you know the name of the method and all input arguments as Object array. The amazing part is MethodUtil can find that method and call that method with auto-boxing:

MethodUtils.invokeMethod(obj, methodName, args)

This method search for the method by the name of the method and type specified in args, it does “auto-boxing” magically, therefore Integer is the same as int and Integer[] is the same as int[]. Basically, when using this method, you can simple call the method you want to call with wrapper objects and wrapper arrays.

Posted in: Development