Java Reflection API Example - Method Invocation

Java Reflection API :

Java Reflection API is a powerfull and advanced API ( part of JRE ) , which can be used to deal with Java Classes at runtime rather than at compile time.

Realtime Usages :

1) Spring uses Reflection API for dependency injection .

2) JUnit Framework uses reflection API to detect methods annotated with @Test annotation.

3) Eclipse does auto-completion of method names etc using Reflection API.

4) Some tools uses reflection API to call setters and getters of POJO or Bean Classes.

Example : Method invocation using Reflection AP

Some class with two methods as shown.

public class SomeClass {
    // method with no parameters
    public void test() {
        System.out.println("test() called");

    // method with int and Double parameters
    public void add(int i, Double j) {
        System.out.println("addition result : " + (i + j));

Here , we use reflection API to invoke/call methods of .

package com.demo.fileuploaddemo;

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

public class ReflectionDemo {

    public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException,
                    IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        // Class instance of SomeClass
        Class<?> c = SomeClass.class;

        // Create new object from Class
        Object obj = c.newInstance();

        // invoke/call add(int,Double) method
        Method m1 = c.getDeclaredMethod("add", int.class, Double.class);
        m1.invoke(obj, 1, 2.3);

        // invoke/call test() method
        Method m2 = c.getDeclaredMethod("test");
addition result : 3.3
test() called



Submit a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>