Saturday 16 August 2014

Invoke static methods using Reflection

Procedure is similar like previous post, except, you supply null instead of an object instance for the 'invoke' method.

public class Add {
    static int add(int a, int b){
        return (a+b);
    }
    
    static int add(int a, int b, int c){
        return a+b+c;
    }
    
    static float add(float a, float b){
        return (a+b);
    }
    
    static 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(null, 1, 2);
        System.out.println(result);
        
        method = myClass.getDeclaredMethod("add", float.class, float.class);
        result = method.invoke(null, 1.05f, 2.07f);
        System.out.println(result);
        
        method = myClass.getDeclaredMethod("add", int.class, int.class, int.class);
        result = method.invoke(null, 1, 2, 3);
        System.out.println(result);
        
        method = myClass.getDeclaredMethod("add", float.class, float.class, float.class);
        result = method.invoke(null, 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