Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke a method in java using reflection

How can I invoke a method with parameters using reflection ?

I want to specify the values of those parameters.

like image 362
Steven Avatar asked Mar 09 '10 06:03

Steven


2 Answers

Here's a simple example of invoking a method using reflection involving primitives.

import java.lang.reflect.*;

public class ReflectionExample {
    public int test(int i) {
        return i + 1;
    }
    public static void main(String args[]) throws Exception {
        Method testMethod = ReflectionExample.class.getMethod("test", int.class);
        int result = (Integer) testMethod.invoke(new ReflectionExample(), 100);
        System.out.println(result); // 101
    }
}

To be robust, you should catch and handle all checked reflection-related exceptions NoSuchMethodException, IllegalAccessException, InvocationTargetException.

like image 67
polygenelubricants Avatar answered Nov 01 '22 12:11

polygenelubricants


To call a class method using reflection is very simple. You need to create a class and generate method in it. like as follows.

package reflectionpackage;

public class My {
    public My() {
    }

    public void myReflectionMethod() {
        System.out.println("My Reflection Method called");
    }
}

and call this method in another class using reflection.

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

public class ReflectionClass {

    public static void main(String[] args) 
    throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Class c=Class.forName("reflectionpackage.My");
        Method m=c.getDeclaredMethod("myReflectionMethod");
        Object t = c.newInstance();
        Object o= m.invoke(t);       
    } 
}

Find more details here.

like image 44
sumit sharma Avatar answered Nov 01 '22 11:11

sumit sharma