A Simple Reflection Example


import java.lang.reflect.Method;
public class SimpleReflection {
	public static void main(String[] args) throws Exception {
		// ================================================
		// The code in this method is equivalent to the following lines of code
		// ————————————————-
		// reflection.Echo echo = new reflection.Echo()
		// String retStr = echo.echo("Muneeb")
		// =================================================

		String className = "reflection.Echo";
		String methodName = "echo";
		Class clazz = Class.forName(className);
		Object obj = clazz.newInstance();

		Class methodParamTypes[] = new Class [1];
		Object methodParamObjects[] = new Object[1];

		methodParamTypes[0] = String.class;
		methodParamObjects[0] = new String("Muneeb");

		Method classMethod = clazz.getMethod(methodName, methodParamTypes);
		Object retObj = classMethod.invoke(obj, methodParamObjects);

		String retStr = (String) retObj;		

		System.out.println("respStr = " + retStr);

	}
}

You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

AddThis Social Bookmark Button

Similar Posts

Comments are closed.