Java reflection, is the very useful concept used by maximum professional to get the run time flexibility of calling or getting the necessary information about particular java class. It may be inbuilt JAVA class or user defined class. Reflections are mostly used in eclipse or any Java editor to provide intellisens like features.
In below example, we have created a method named add(int a, int b) which is called by reflection property.
to invoke method using java reflection method.invoke(classObj, arglist) is used.
package com.shivasoft.evening.reflection; import java.lang.reflect.Method; public class InvokeDemo { public int add(int a, int b) { return a+b; } public static void main(String[] args) throws Exception { Class c = Class.forName("com.shivasoft.evening.reflection.InvokeDemo"); Class[] parTypes = new Class[2]; parTypes[0] = Integer.TYPE; parTypes[1] = Integer.TYPE; //Get reference of add method Method m = c.getMethod("add", parTypes); Object[] argList = new Object[2]; argList[0] = 40; argList[1] = 90; InvokeDemo obj = new InvokeDemo(); System.out.println(m.invoke(obj,argList)); } }
Output of the above program is: 130
Leave a Reply