Java Reflection ExampleThis snippet shows how to invoke a method of class using Java Reflection API. The example uses a class called TargetClass that has a instance method named as runMe(). Now from the main method, this class will be loaded via the System Classloader and then instantiated using the newInstance() method. Then finally using the Reflection API and then the runMe() method would be invoked on created instance.
package com.livrona.snippets.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

 * This snippet shows how to invoke a method of class using Java Reflection API.
 * @author java4learners
public class Reflection {

	 * Main method for testing.
	 * @param args
	 * @throws ClassNotFoundException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	public static void main(String args[])
			throws // a fit
			ClassNotFoundException, InstantiationException,
			IllegalAccessException, NoSuchMethodException,

		ClassLoader j = ClassLoader.getSystemClassLoader();
		Class someClass = j.loadClass("TargetClass");
		Object instanceOfSomething = someClass.newInstance();

		// note, the second param is null since the runMe method takes no
		// parameters
		Method aMethod = someClass.getMethod("runMe", null);

		// again, a null second parameter since runMe has no params
		Object returnValue = aMethod.invoke(instanceOfSomething, null);

		System.out.println("return value of runMe : " + returnValue);

	}// main

}// class

class TargetClass {
	public int runMe() {
		System.out.println("runMe() in Target class has been invoked!");

		return 1; // just to check if return values work