Java Reflection
In this tutorial we will see about Java Reflection and how to use. Java Reflection is a important topic and need to use only when its necessary in our programming. It deals with class and methods at run-time and as its API we need to include necessary classes in our program.
Java reflection is used in most of application and frameworks. For example JUnit is most commonly used for unit testing by the programmers. Where we used to specify the methods with @Test annotation which will mark to the JUnit as testcase and will be executed automatically by calling corresponding class and methods using Java Reflection.
Lets see small example of Java Reflection by parameter and without parameter.
class MyClass{ public void simpleMethod(){ System.out.println("Hi, inside simple method..."); } public void methodWithStringParam(String name){ System.out.println("Hi, "+name); } public void methodWithIntParam(int value){ System.out.println("Value passed : "+value); } public void methodWith2Param(String name1, int value){ System.out.println("Hi, "+name1+" & "+value); } public String methodWithReturn(){ return "Java Discover"; } }
import java.lang.reflect.Method;
public class ReflectionTesting {
public static void main(String[] args) { try { // Create class instance at runtime Class cls = Class.forName("com.test.MyClass"); Object obj = cls.newInstance(); // Calling method simpleMethod() without parameters Class param1[] = {}; Method method = cls.getDeclaredMethod("simpleMethod", param1); method.invoke(obj, null); // Calling method methodWithStringParam() with String parameter Class param2[] = new Class[1]; param2[0] = String.class; method = cls.getDeclaredMethod("methodWithStringParam", param2); method.invoke(obj, new String("Java Discover")); // Calling method methodWithIntParam() with String parameter Class param3[] = new Class[1]; param3[0] = Integer.TYPE; method = cls.getDeclaredMethod("methodWithIntParam", param3); method.invoke(obj, 1000); // Calling method methodWith2Param() with String and Integer parameters Class param4[] = new Class[2]; param4[0] = String.class; param4[1] = Integer.TYPE; method = cls.getDeclaredMethod("methodWith2Param", param4); method.invoke(obj, new String("Java Discover"), 2006); // Calling method methodWithReturn() with return method = cls.getDeclaredMethod("methodWithReturn", param1); String rValue = (String)method.invoke(obj, null); System.out.println("Returned value : "+rValue); } catch (Exception e) { e.printStackTrace(); } } }
OUTPUT:
Hi, inside simple method... Hi, Java Discover Value passed : 1000 Hi, Java Discover & 2006 Returned value : Java Discover