Saturday 16 August 2014

Invoke Method using Method Object

Invoking a method using reflection is two step process.

Step 1: Get the Method object, using 'getDeclaredMethod', or 'getMethod' of Class object.
     Example
    Class myClass = Class.forName("Add");
    Add obj = new Add();
    Method method = myClass.getDeclaredMethod("add", int.class, int.class);

myClass.getDeclaredMethod("add", int.class, int.class)
In the above statement, first argument, 'add' specifies the method name, and remaining arguments represent parameter types of this method.

Step 2: Invoke the method by using the Method object you got in Step1.
    Example
    Object result = method.invoke(obj, 1, 2);

public class Add {
    int add(int a, int b){
        return (a+b);
    }
    
    int add(int a, int b, int c){
        return a+b+c;
    }
    
    float add(float a, float b){
        return (a+b);
    }
    
    float add(float a, float b, float c){
        return (a+b+c);
    }
}

import java.lang.reflect.*;

public class RunMethod {
    public static void main(String arg[]) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
        Class myClass = Class.forName("Add");
        Add obj = new Add();
        
        Method method = myClass.getDeclaredMethod("add", int.class, int.class);
        Object result = method.invoke(obj, 1, 2);
        System.out.println(result);
        
        method = myClass.getDeclaredMethod("add", float.class, float.class);
        result = method.invoke(obj, 1.05f, 2.07f);
        System.out.println(result);
        
        method = myClass.getDeclaredMethod("add", int.class, int.class, int.class);
        result = method.invoke(obj, 1, 2, 3);
        System.out.println(result);
        
        method = myClass.getDeclaredMethod("add", float.class, float.class, float.class);
        result = method.invoke(obj, 1.05f, 2.07f, 3.06f);
        System.out.println(result);
    }
}

Output
3
3.12
6
6.18



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment