Invoke method using reflection in JAVA

Author posted by Jitendra on Posted on under category Categories JAVA and tagged as Tags , , with 1 Comment on Invoke method using reflection in JAVA

Invoke method using reflection in JAVA

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

Related posts

One thought on “Invoke method using reflection in JAVA”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.