This 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.<!--break-->
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
*
*/
publicclass Reflection {
/**
* Main method for testing.
* @param args
* @throws ClassNotFoundException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws NoSuchMethodException
* @throws InvocationTargetException
*/
publicstaticvoid main(String args[])
throws// a fit
ClassNotFoundException, InstantiationException,
IllegalAccessException, NoSuchMethodException,
InvocationTargetException
{
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 {
publicint runMe() {
System.out.println("runMe() in Target class has been invoked!");
return1; // just to check if return values work
}
}