Java Reflection Method Invoke invokeMethod(Object obj, String methodName, Object... args)

Here you can find the source of invokeMethod(Object obj, String methodName, Object... args)

Description

invoke Method

License

Open Source License

Declaration

public static Object invokeMethod(Object obj, String methodName, Object... args) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

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

public class Main {
    public static Object invokeMethod(Object obj, String methodName, Object... args) {
        try {/*from w w  w .  j a v a2 s.  c  o m*/
            Method m;
            if (args != null) {
                Class<?>[] argClasses = new Class<?>[args.length];
                for (int i = 0; i < args.length; i++)
                    argClasses[i] = args[i].getClass();
                m = obj.getClass().getMethod(methodName, argClasses);
                return m.invoke(obj, args);
            } else {
                m = obj.getClass().getMethod(methodName);
                return m.invoke(obj);
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        throw new RuntimeException("Error!");
    }

    public static Class<?> getClass(String className) {
        try {
            if (className == null)
                return null;
            else
                return Class.forName(className);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException("Error in instantiating class: " + className);
        }
    }
}

Related

  1. invokeMethod(Object obj, Method method, Object... args)
  2. invokeMethod(Object obj, String mehtodName, Object... parameter)
  3. invokeMethod(Object obj, String method)
  4. invokeMethod(Object obj, String method, Object... args)
  5. invokeMethod(Object obj, String methodName, Object... args)
  6. invokeMethod(Object obj, String methodname, Object... args)
  7. invokeMethod(Object obj, String methodName, Object... params)
  8. invokeMethod(Object obj, String methodName, Object[] params, Class[] paramTypes)
  9. invokeMethod(Object object, Method method, Object... args)