Java Reflection Method Invoke invokeMethod(Object obj, String mehtodName, Object... parameter)

Here you can find the source of invokeMethod(Object obj, String mehtodName, Object... parameter)

Description

invoke Method

License

Open Source License

Declaration

@SuppressWarnings("unchecked")
    public static Object invokeMethod(Object obj, String mehtodName, Object... parameter) 

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 {
    @SuppressWarnings("unchecked")
    public static Object invokeMethod(Object obj, String mehtodName, Object... parameter) {
        Class c = obj.getClass();
        Method method = null;/*from ww w .j  a v  a  2s  .com*/
        Object result = null;
        if (parameter == null) {
            try {
                method = c.getMethod(mehtodName, new Class[] {});
                result = method.invoke(obj, new Object[] {});
            } 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();
            }
        } else {
            Class[] clas = new Class[parameter.length];
            for (int i = 0; i < parameter.length; i++) {
                clas[i] = parameter[i].getClass();
            }
            try {
                method = c.getMethod(mehtodName, clas);
                result = method.invoke(obj, parameter);
            } 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();
            }

        }
        return result;
    }
}

Related

  1. invokeMethod(Object o, String fieldName)
  2. invokeMethod(Object o, String methodName, Object... args)
  3. invokeMethod(Object o, String methodName, Object[] params)
  4. invokeMethod(Object obj, Class type, String name, Class[] parameterTypes, Object[] parameters)
  5. invokeMethod(Object obj, Method method, Object... args)
  6. invokeMethod(Object obj, String method)
  7. invokeMethod(Object obj, String method, Object... args)
  8. invokeMethod(Object obj, String methodName, Object... args)
  9. invokeMethod(Object obj, String methodName, Object... args)