Main Tutorials

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

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
25 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Nayana
6 years ago

What if my AppTest class does not have a default constructor? How can I pass the parameters to the constructor while creating newInstance ?

Juliana Galarraga
7 years ago

Thank you mkyong!! Very helpful!! ^__^

rameshwari
8 years ago

hi mkyong
I want a main class in which I want a list of methods which contains a particular connection. how to get it.

Dinesh
8 years ago

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

mani
9 years ago

Please show me how to get the path of current working work space along with the project name without using main method…i don have any main method in my entire project…iam getting the eclipse location path but not the workspace path when i am running “System.getProperty(“user.dir”);” in a method…Thanks in Advance 🙂

Krishna Chaitanya Bommisetty
10 years ago

Simple and clear.. Thanks

AbdulBasit Shaikh
10 years ago

Very Nice Document…thanks mkyong…

David Wang
10 years ago

one problem. If you create an instance as apptest, then use apptest.setCounter(100000); then try to invoke printCounter, then you still get 999. Any way to solve it?
thanks

Abd El-Hameed
10 years ago

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.

Benerjee
10 years ago

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

s@n h@q
10 years ago
Reply to  Benerjee

This might help you.

public class AppTest{

private int counter;

……..

public int getCounter(){
return this.counter;
}

}

public class ReflectApp{
main(){

method = cls.getDeclaredMethod(“getCounter”, noparam);
Integer counter = (Object)method.invoke(obj, null);

}

}

Nivedha
10 years ago

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

abc
10 years ago

hi

anuj
10 years ago

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:-) !!

Moises
10 years ago

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
11 years ago

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

ss
11 years ago

i want example program for constructor reflection

BASANT KUMAR
11 years ago
Reply to  ss

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
11 years ago

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

Janu
10 years ago
Reply to  Pablo

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
10 years ago
Reply to  Janu

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.

Vivek
12 years ago

How reflection is useful for Spring and Hibernate?

Parag
12 years ago

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?

IhateMyJobBecauseOfThem
6 years ago

Don’t use reflection. Classes and framework are designed in a way where private and protected have a meaning. If you break this meaning, then go write script languages. In Android P for example, using this kind of code will now throw some exception (and it is good! fuck those that used this before).

The only and ONLY use case I allow, is where you have to write debugging tools, make tools that inspect code etc. But mostly of the time, another solution exists. Poor developpers, they are so lazy that they don’t care about private or protected. They don’t write code, they use library. Poor mans.

lalit
6 years ago

hi im new to java.
say like student.getSubject() have “java”, could I get the value, if I use like following code?

String appending = “getSubject()”;
System.out.println(“student.”.concat(appending));