Monday, May 13, 2013

Java Reflection API: Calling methods

Moving forward from my previous article: Java Reflection API: Constructing Objects

Using Java Reflection you can inspect the methods of classes and invoke them at runtime. This is done via the Java class java.lang.reflect.Method. Below are the details to achieve the same:

Obtaining Methods
You can obtain the methods from the Class object:
Method[] methods = mClass.getMethods();

The Method[] array will have one Method instance for each public method declared in the class.

If you know the precise parameter types of the method you want to access, you can do so rather than obtain the array of all methods. This example returns the public method named "mMethod", in the given class which takes a String as parameter:
Method method = mClass.getMethod("mMethod", new Class[]{String.class});
If the method trying to access takes no parameters, pass null as the parameter type array:
Method method = mClass.getMethod("mMethod", null);
Parameters and Return types
To access details about method parameters and return types, do the below:
Class[] parameterTypes = method.getParameterTypes();

Class returnType = method.getReturnType();
Calling methods

The null parameter is the object you want to invoke the method on. If the method is static you supply null instead of an object instance. In this example, if mMethod(String.class) is not static, you need to supply a valid mObject instance instead of null;

The Method.invoke(Object target, Object ... parameters) method takes an optional amount of parameters, but you must supply exactly one parameter per argument in the method you are invoking. In this case it was a method taking a String, so one String must be supplied.
Method method = mClass.getMethod("mMethod", String.class);
Object returnValue = method.invoke(null, "value-1");


3 comments: