Apr 27, 2012

Invoke methods of an object using reflection

How to invoke methods of class using reflection


Reflection helps in getting all the information of a class from a Java program. The use of reflection also helps in invoking the methods present in a class by passing the appropriate arguments when invoking the method.

The following program shows how methods of a class can be invoked by using reflection in Java.



package com.example;

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

class ABC{
public void test(String str) {
System.out.println(str);
}
}

/** This class is a Java tutorial for invoking methods from classes using reflection in Java
*
* @author Extreme Java
*/
public class Test{

/** This method shows how to use invoke methods using reflection in Java
*
* @param args
*/
public static void main(String[] args) {

Class ABC = ABC.class;

Method[] methods = ABC.getDeclaredMethods();

ABC abc = new ABC();

for (Method method : methods) {
Object result;
try {
method.invoke(abc, "Hello World");
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
return;
} catch (InvocationTargetException ex) {
ex.printStackTrace();
return;
} catch (IllegalAccessException ex) {
ex.printStackTrace();
return;
}
}
}
}


output:
Hello World

The output shows that the method test() of ABC class has been invoked and had there been multiple methods present in the class, all those would have been invoked.

No comments:

Post a Comment