Wednesday, March 28, 2012

Java : Simple Refection API example

In Java, have you ever needed to call a method at Run time. i.e. A method should be called depending upon some parameter at runtime, you dont know the methods name at compile time. If your answer is yes then Java Reflection API is the best way to proceed, However it has few disadvantage as well.

Java's Reflection API's makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time.

To know about about Reflection API, click here

Invoking Methods using Method Object

Method method = MyClass.class.getMethod("methodName", Object... parameter);
Object returnValue = method.invoke(MyClassObject, "parameterValue");

Loading Class

You can load Class if you know the class name while compile time as shown below.

Class classObject = MyClass.class;

Else you can also load class at run time as shown below.

Note: This may throw ClassNotFoundException if fully qualified class name is not found.

Class classObject = Class.forName("com.MyClass");

Lets see a simple runnable example on this.
/* TestReflection.java */

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TestReflection 
{
 public String Add(int param1,int param2) {
  return "Addition : "+(param1 + param2);
 }

 public String Subtract(int param1,int param2) {
  return "Subtraction : "+(param1 - param2);
 }
 public static void main(String[] args)  throws SecurityException, 
NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
InvocationTargetException
 {
  TestReflection t = new TestReflection();

  //String methodToCall = "Add";
  String methodToCall = "Subtract";

  Method m = TestReflection.class.getMethod(methodToCall, int.class,int.class);

  String returnVal = (String) m.invoke(t, 3,2);

  System.out.println(returnVal);
 }
}


Note : If JVM is not able to find method name then it will throw NoSuchMethodException exception

Exception in thread "main" java.lang.NoSuchMethodException: TestReflection.unknownMethod(int, int)
        at java.lang.Class.getMethod(Unknown Source)
        at TestReflection.main(TestReflection.java:21)

No comments:

Post a Comment