Java Programming/Reflection/Dynamic Invocation

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search
Navigate Reflection topic:

We start with basic transfer object


package com.test;
 
public class DummyTo {
String name;
String address;
public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}
public String getAddress() {
	return address;
}
public void setAddress(String address) {
	this.address = address;
}
public DummyTo(String name, String address) {
 
	this.name = name;
	this.address = address;
}
 
public DummyTo() {
 
	this.name = new String();
	this.address = new String();
}
 
public String toString(String appendBefore)
{
	return appendBefore+" "+name+" , "+address;
 
}
 
}

Following is the example for invoking method from the above mentioned to dynamically. Code is self explanatory


package com.test;
 
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
 
public class ReflectTest {
public static void main(String[] args)
{
	try {
		Class dummyClass = Class.forName("com.test.DummyTo");
 
		//parameter types for methods
		Class[] partypes = new Class[]{String.class};
 
                //Create method object . methodname and parameter types
                Method meth = dummyClass.getMethod("toString", partypes);
 
		//parameter types for constructor
		Class[] constrpartypes = new Class[]{String.class, String.class};
 
                //Create constructor object . parameter types
                Constructor constr = dummyClass.getMethod(constrpartypes);
 
                //create instance
		Object dummyto = constr.newInstance(new String[]{"Java Programmer", "India"});
 
                //Arguments to be passed into method
                Object[] arglist = new Object[]{"I am"};
 
                //invoke method!!
		String output = (String) meth.invoke(dummyto, arglist);
		System.out.println(output);
 
	} catch (ClassNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (SecurityException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (NoSuchMethodException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IllegalArgumentException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IllegalAccessException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (InvocationTargetException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
}

Conclusion  :

  Above examples demonstrate the invocation of method dynamically using reflection