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 the Author

author image
mkyong
Founder of Mkyong.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

Leave a Reply

avatar
newest oldest most voted
whore
Guest
whore

super whore

IhateMyJobBecauseOfThem
Guest
IhateMyJobBecauseOfThem
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… Read more »
lalit
Guest
lalit

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

Nayana
Guest
Nayana

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
Guest
Juliana Galarraga

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

rameshwari
Guest
rameshwari

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
Guest
Dinesh

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

mani
Guest
mani

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
Guest
Krishna Chaitanya Bommisetty

Simple and clear.. Thanks

AbdulBasit Shaikh
Guest
AbdulBasit Shaikh

Very Nice Document…thanks mkyong…

trackback
Java Custom Annotations | ER`Archives

[…] Notice in the method.invoke, I’ve passed two parameters. An object, and an array of objects. The first parameter is an object of the class where you’re going to use the annotation. You can get a clear idea about what that means from here. […]

David Wang
Guest
David Wang

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
Guest
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.

Benerjee
Guest
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

s@n h@q
Guest
s@n h@q

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
Guest
Nivedha

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

abc
Guest
abc

hi

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

Moises
Guest
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
Guest
Akhilesh Dubey

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

ss
Guest
ss

i want example program for constructor reflection

BASANT KUMAR
Guest
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
Guest
Pablo

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

Janu
Guest
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
Guest
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… Read more »
Vivek
Guest
Vivek

How reflection is useful for Spring and Hibernate?

Parag
Guest
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?