Reflection is a very useful approach to deal with the Java class at runtime, it can be use to load the Java class, call its methods or analysis the class at runtime.

In this example, you will load a class called “AppTest” and call each of its methods at runtime.


This Java class and its methods will be call at runtime later

package com.mkyong.reflection;
public class AppTest{
	private int counter;
	public void printIt(){
		System.out.println("printIt() no param");
	public void printItString(String temp){
		System.out.println("printIt() with param String : " + temp);
	public void printItInt(int temp){
		System.out.println("printIt() with param int : " + temp);
	public void setCounter(int counter){
		this.counter = counter;
		System.out.println("setCounter() set counter to : " + counter);
	public void printCounter(){
		System.out.println("printCounter() : " + this.counter);


This class will load the “AppTest” class and call its methods at runtime. The codes and comments are self-explanatory.

package com.mkyong.reflection;
import java.lang.reflect.Method;
public class ReflectApp{
	public static void main(String[] args) {
	//no paramater
	Class noparams[] = {};
	//String parameter
	Class[] paramString = new Class[1];	
	paramString[0] = String.class;
	//int parameter
	Class[] paramInt = new Class[1];	
	paramInt[0] = Integer.TYPE;
	        //load the AppTest at runtime
		Class cls = Class.forName("com.mkyong.reflection.AppTest");
		Object obj = cls.newInstance();
		//call the printIt method
		Method method = cls.getDeclaredMethod("printIt", noparams);
		method.invoke(obj, null);
		//call the printItString method, pass a String param 
		method = cls.getDeclaredMethod("printItString", paramString);
		method.invoke(obj, new String("mkyong"));
		//call the printItInt method, pass a int param
		method = cls.getDeclaredMethod("printItInt", paramInt);
		method.invoke(obj, 123);
		//call the setCounter method, pass a int param
		method = cls.getDeclaredMethod("setCounter", paramInt);
		method.invoke(obj, 999);
		//call the printCounter method
		method = cls.getDeclaredMethod("printCounter", noparams);
		method.invoke(obj, null);
	}catch(Exception ex){

3. Output

printIt() no param
printIt() with param String : mkyong
printIt() with param int : 123
printCounter() : 999
Tags :
Founder of, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.
My website is hosted by Liquid Web, I really like their fast and helpful support, it saved me a lot of time. Furthermore, their servers are extremely reliable, fast and stable, I don't remember when was the last time we had server downtime. Btw, they're offering $100 Coupon now, if you are sourcing for great hosting provider, go grab it.

Related Posts

Popular Posts