Java Reflection Method Invoke invokeMethod(Method method, Object target)

Here you can find the source of invokeMethod(Method method, Object target)

Description

invoke Method

License

Apache License

Declaration

public static Object invokeMethod(Method method, Object target) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

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

import java.lang.reflect.UndeclaredThrowableException;

public class Main {
    public static Object invokeMethod(Method method, Object target) {
        return invokeMethod(method, target, new Object[0]);
    }//from  w  w w.j a va 2 s  .  co m

    public static Object invokeMethod(Method method, Object target, Object... args) {
        try {
            return method.invoke(target, args);
        } catch (Exception ex) {
            handleReflectionException(ex);
        }
        throw new IllegalStateException("Should never get here");
    }

    public static void handleReflectionException(Exception ex) {
        if (ex instanceof NoSuchMethodException) {
            throw new IllegalStateException("Method not found: " + ex.getMessage());
        }
        if (ex instanceof IllegalAccessException) {
            throw new IllegalStateException("Could not access method: " + ex.getMessage());
        }
        if (ex instanceof InvocationTargetException) {
            handleInvocationTargetException((InvocationTargetException) ex);
        }
        if (ex instanceof RuntimeException) {
            throw (RuntimeException) ex;
        }
        throw new UndeclaredThrowableException(ex);
    }

    public static void handleInvocationTargetException(InvocationTargetException ex) {
        rethrowRuntimeException(ex.getTargetException());
    }

    public static void rethrowRuntimeException(Throwable ex) {
        if (ex instanceof RuntimeException) {
            throw (RuntimeException) ex;
        }
        if (ex instanceof Error) {
            throw (Error) ex;
        }
        throw new UndeclaredThrowableException(ex);
    }
}

Related

  1. invokeMethod(Method method, Object instance, Object... parameters)
  2. invokeMethod(Method method, Object object)
  3. invokeMethod(Method method, Object object, Object... args)
  4. invokeMethod(Method method, Object object, Object... arguments)
  5. invokeMethod(Method method, Object target)
  6. invokeMethod(Method method, Object target)
  7. invokeMethod(Method method, Object target, Class expectedType)
  8. invokeMethod(Method method, Object target, Object... args)
  9. invokeMethod(Method method, Object target, Object... args)