Java Reflection Method Invoke invokeMethodByName(final Object obj, final String methodName, final Object[] args)

Here you can find the source of invokeMethodByName(final Object obj, final String methodName, final Object[] args)

Description

invoke Method By Name

License

Apache License

Declaration

public static Object invokeMethodByName(final Object obj, final String methodName, final Object[] args) 

Method Source Code


//package com.java2s;
/*//from  w  ww . ja va 2 s .  com
 * Copyright (c) 2015-2020, Chen Rui
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

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

public class Main {
    private static final String CGLIB_CLASS_SEPARATOR = "$$";

    public static Object invokeMethodByName(final Object obj, final String methodName, final Object[] args) {
        Method method = getAccessibleMethodByName(obj, methodName);
        if (method == null) {
            throw new IllegalArgumentException(
                    "Could not find MethodDefine [" + methodName + "] on target [" + obj + "]");
        }

        try {
            return method.invoke(obj, args);
        } catch (Exception e) {
            throw convertReflectionExceptionToUnchecked(e);
        }
    }

    public static Method getAccessibleMethodByName(final Object obj, final String methodName) {
        for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType
                .getSuperclass()) {
            Method[] methods = searchType.getDeclaredMethods();
            for (Method method : methods) {
                if (method.getName().equals(methodName)) {
                    makeAccessible(method);
                    return method;
                }
            }
        }
        return null;
    }

    public static RuntimeException convertReflectionExceptionToUnchecked(Exception exception) {
        if ((exception instanceof IllegalAccessException) || (exception instanceof IllegalArgumentException)
                || (exception instanceof NoSuchMethodException)) {
            return new IllegalArgumentException(exception);
        } else if (exception instanceof InvocationTargetException) {
            return new RuntimeException(((InvocationTargetException) exception).getTargetException());
        } else if (exception instanceof RuntimeException) {
            return (RuntimeException) exception;
        }
        return new RuntimeException("Unexpected Checked Exception.", exception);
    }

    public static Class<?> getSuperClass(Object instance) {
        Class clazz = instance.getClass();
        if ((clazz != null) && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) {
            Class<?> superClass = clazz.getSuperclass();
            if ((superClass != null) && !Object.class.equals(superClass)) {
                return superClass;
            }
        }
        return clazz;

    }

    public static void makeAccessible(Method method) {
        if ((!Modifier.isPublic(method.getModifiers())
                || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) && !method.isAccessible()) {
            method.setAccessible(true);
        }
    }

    public static void makeAccessible(Field field) {
        if ((!Modifier.isPublic(field.getModifiers())
                || !Modifier.isPublic(field.getDeclaringClass().getModifiers())
                || Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
            field.setAccessible(true);
        }
    }
}

Related

  1. invokeMethod2(Class cls, Object obj, String methodName, Object[] args)
  2. invokeMethodAndGet(Object object, String methodName, Object... args)
  3. invokeMethodAndGetRecursively(Object object, String methodName, Object... args)
  4. invokeMethodAndReturn(Class clazz, String method, Object object)
  5. invokeMethodByName(@Nonnull T object, @Nonnull String name, Class typeArg, Object arg)
  6. invokeMethodHandleException(Method method, Object... args)
  7. invokeMethodNoArgs(final Object obj, final String methodName, final Class... returnTypePreference)
  8. invokeMethodNoArgs(Object target, String methodName)
  9. invokeMethodOfClass(Class target, Method method)