lundi 22 mai 2017

Best way to use reflection to call different methods of a class in a single utility method

I have a class with multiple methods which accepts different params and return different type like class foo in below example:-

class foo{
    public void A(int a , int b){
      // do somthing.
    }

    public String B(int a , String b){
        // do somthing.
        return "a";
    }

    public Object C(String a , String b){
        // do somthing.
        return null;
    }

    public int D(Long a , String b , String c){
        // do somthing.
        return 1;
    }
}
public class bar {

    public static void main(String[] args) {

        try {
            Class c = Class.forName("foo");
            Object t = c.newInstance();
            Method[] methods = c.getDeclaredMethods();
            for(Method m : methods){
                String methodName = m.getName();
                if(methodName.equalsIgnoreCase("A")) {
                    // How to call method with its argument and return the result using reflection.
                    m.invoke(t,);
                    break;
                }
            }

        }catch (InstantiationException e){

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // Handle any exceptions thrown by method to be invoked.
            e.printStackTrace();
        }

    }

}

Now i want to create a utility method which accepts the method name and arguments and call the corresponding method using the reflection. Let me know how can i pass different method params using the generic utility method and return the result(it may return int,string,object as illustrated in the example) from the reflection code.





Aucun commentaire:

Enregistrer un commentaire