How to use Reflection to call Java method at runtime

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.

1. AppTest.java

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);
	}
}

2. ReflectApp.java

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;
 
	try{
	        //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){
		ex.printStackTrace();
	}
   }
}

3. Output

printIt() no param
printIt() with param String : mkyong
printIt() with param int : 123
printCounter() : 999
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, 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.

Comments

  • Pingback: Java Custom Annotations | ER`Archives()

  • Abd El-Hameed

    Can this kind of Refelction help me with my APP

    I am developing and Android app which is divided between 2 (or more) devices. One should be the server which the client should ask it to perform a process on data. Both process and data should be sent from client to server.

    I wonder how to dynamically load the process (dex class?OK, any suggestions) from the client to the server.

    In other words. Server knows what to do at run-time. It’s a kind of RPC but the procedure itself should be send to the server.

    Any Suggestions. Thanks on advance.

  • http://ramben.in Benerjee

    Hi MkYong,
    Thanks for this example but I NEED TO CALL A GETTER METHOD. i.e., I NEED TO GET THE RETURN VALUE AFTER REFLECTION.
    So can you please post that to my mail or in this blog.
    Thanks & Regards,
    G.s.s.Benerjee

  • Nivedha

    hi..this code helps me very much for my automation process..thank you..

  • abc

    hi

  • anuj

    You are simply awesome mkyong. Many a times I have been struggling to find ways as how to use some code and then have found them brilliantly explained here. You rock man:-) !!

  • http://- Moises

    Hi mkyong !! Help-me please !! (by god !)

    How i call a simple setString method from a PreparedStatement instance ?

    I try all, but i canĀ“t !!

    See:

    public PreparedStatement getPreparedStatement(Connection conexao, String sqlStatement) throws …..{

    java.sql.PreparedStatement prepstm = conexao.prepareStatement(sqlStatement);

    int i = 0;
    String method = null;
    Object value = null;
    Class valueType = null;

    Class cls = prepstm.getClass();

    for(int j = 0; j< cls.getMethods().length; j++){
    //System.out.println(cls.getMethods()[j]);

    if((cls.getMethods()[j]).toString().contains("setString")){
    System.out.println(j);

    cls.getMethods()[j].invoke("setString", ????????????? );

    }

    }

    thanks for help

  • Akhilesh Dubey

    Hello, i get java.lang.IllegalArgumentException: argument type mismatch at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)… why so ?

  • http://www.mkyong.com/java/how-to-use-reflection-to-call-java-method-at-runtime/ ss

    i want example program for constructor reflection

    • BASANT KUMAR

      package singaltonconstructor;

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

      public class B
      {
      public static void main(String args[]) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
      {
      Constructor c = A.class.getDeclaredConstructor();
      c.setAccessible(true);
      c.newInstance();
      }
      }

      public class A
      {
      private A()
      {
      System.out.println(“private constructor calling OF class A”);
      }
      }

  • Pablo

    Hello, I’ve heard that using reflection it’s not secure at all … what do you think about this? do you agree?

    • Janu

      Hi, ya i think its true, because by knowing just name of a class you can access all members, methods, constructors of a class. Then how its secure at all????? So reflection is not secure…

      • crow

        Ya but if you know the name of the class and the member in it you can your self create a object of that class without using reflection and call the methods on it. So in both cases it is the same thing . You need to know the class definition . The real significance of reflection lies in concepts where a user can choose their own name of methods and parameters but the functionality at core remains the same , for example in web services. API’s which we use in concept like this use reflection to provide you an implementation to make RPC calls.

  • http://www.facebook.com/coervivek Vivek

    How reflection is useful for Spring and Hibernate?

  • http://www.paragarora.com Parag

    Seems like class has to implement the method in its class. What if this class extends an abstract class and we need to call a function implemented in this abstract class?