Java Reflection Method Invoke invokeMethodNoArgs(final Object obj, final String methodName, final Class... returnTypePreference)

Here you can find the source of invokeMethodNoArgs(final Object obj, final String methodName, final Class... returnTypePreference)

Description

Invoke a method without arguments, get the method matching the return types best, i.e.

License

Open Source License

Parameter

Parameter Description
obj a parameter
methodName a parameter
returnTypePreference Most preferred return type first, might return null, might return a method with a completely different return type, comparison with ==, no isAssignableForm. TODO: really ?

Declaration

public static Object invokeMethodNoArgs(final Object obj, final String methodName,
        final Class<?>... returnTypePreference) 

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 {
    /**//from w ww.  j av a 2  s  .c o m
     * Invoke a method without arguments, get the method matching the return types best, i.e. first type is preferred. At present a result is returned, even if the return type does not match at all.
     * @param obj
     * @param methodName
     * @param returnTypePreference Most preferred return type first, might return null, might return a method with a completely different return type, comparison with ==, no isAssignableForm. TODO: really ?
     * @return
     */
    public static Object invokeMethodNoArgs(final Object obj, final String methodName,
            final Class<?>... returnTypePreference) {
        // TODO: Isn't there a one-line-call for this ??
        final Class<?> objClass = obj.getClass();
        // Try to get it directly first.
        Method methodFound = getMethodNoArgs(objClass, methodName, returnTypePreference);
        if (methodFound == null) {
            // Fall-back to seek it.
            methodFound = seekMethodNoArgs(objClass, methodName, returnTypePreference);
        }
        // Invoke if found.
        if (methodFound != null) {
            try {
                final Object res = methodFound.invoke(obj);
                return res;
            } catch (Throwable t) {
                // TODO: Throw something !?
                return null;
            }
        } else {
            // TODO: Throw something !?
            return null;
        }
    }

    /**
     * More fail-safe method invocation.
     * @param method
     * @param object
     * @return null in case of failures (!).
     */
    public static Object invokeMethodNoArgs(Method method, Object object) {
        try {
            return method.invoke(object);
        } catch (IllegalAccessException e) {
        } catch (IllegalArgumentException e) {
        } catch (InvocationTargetException e) {
        }
        return null;
    }

    /**
     * Direct getMethod attempt.
     * @param objClass
     * @param methodName
     * @param returnTypePreference
     * @return
     */
    public static Method getMethodNoArgs(final Class<?> objClass, final String methodName,
            final Class<?>... returnTypePreference) {
        try {
            final Method methodFound = objClass.getMethod(methodName);
            if (methodFound != null) {
                if (returnTypePreference == null || returnTypePreference.length == 0) {
                    return methodFound;
                }
                final Class<?> returnType = methodFound.getReturnType();
                for (int i = 0; i < returnTypePreference.length; i++) {
                    if (returnType == returnTypePreference[i]) {
                        return methodFound;
                    }
                }
            }
        } catch (SecurityException e) {
        } catch (NoSuchMethodException e) {
        }
        return null;
    }

    /**
     * Iterate over all methods, attempt to return best matching return type (earliest in array).
     * @param objClass
     * @param methodName
     * @param returnTypePreference
     * @return
     */
    public static Method seekMethodNoArgs(final Class<?> objClass, final String methodName,
            final Class<?>[] returnTypePreference) {
        // Collect methods that might work.
        Method methodFound = null;
        int returnTypeIndex = returnTypePreference.length; // This can be 0 for no preferences given.
        // TODO: Does there exist an optimized method for getting all by name?
        for (final Method method : objClass.getMethods()) {
            if (method.getName().equals(methodName)) {
                final Class<?>[] parameterTypes = method.getParameterTypes();
                if (parameterTypes.length == 0) {
                    // Override the found method if none found yet or if the return type matches the preferred policy.
                    final Class<?> returnType = method.getReturnType();
                    if (methodFound == null) {
                        methodFound = method;
                        for (int i = 0; i < returnTypeIndex; i++) {
                            if (returnTypePreference[i] == returnType) {
                                returnTypeIndex = i;
                                break;
                            }
                        }
                    } else {
                        // Check if the return type is preferred over previously found ones.
                        for (int i = 0; i < returnTypeIndex; i++) {
                            if (returnTypePreference[i] == returnType) {
                                methodFound = method;
                                returnTypeIndex = i;
                                break;
                            }
                        }
                    }
                    if (returnTypeIndex == 0) {
                        // "Quick" return.
                        break;
                    }
                }
            }
        }
        return methodFound;
    }

    /**
     * Fail-safe getMethod.
     * @param clazz
     * @param methodName
     * @param arguments
     * @return null in case of errors.
     */
    public static Method getMethod(Class<?> clazz, String methodName, Class<?>... arguments) {
        try {
            return clazz.getMethod(methodName, arguments);
        } catch (NoSuchMethodException e) {
        } catch (SecurityException e) {
        }
        return null;
    }

    /**
     * Get a method matching one of the declared argument specifications.
     * @param clazz
     * @param methodName
     * @param argumentLists
     * @return The first matching method (given order).
     */
    public static Method getMethod(Class<?> clazz, String methodName, Class<?>[]... argumentLists) {
        Method method = null;
        for (Class<?>[] arguments : argumentLists) {
            method = getMethod(clazz, methodName, arguments);
            if (method != null) {
                return method;
            }
        }
        return null;
    }
}

Related

  1. invokeMethodAndGetRecursively(Object object, String methodName, Object... args)
  2. invokeMethodAndReturn(Class clazz, String method, Object object)
  3. invokeMethodByName(@Nonnull T object, @Nonnull String name, Class typeArg, Object arg)
  4. invokeMethodByName(final Object obj, final String methodName, final Object[] args)
  5. invokeMethodHandleException(Method method, Object... args)
  6. invokeMethodNoArgs(Object target, String methodName)
  7. invokeMethodOfClass(Class target, Method method)
  8. invokeMethodOnLoader(ClassLoader cl, String methodName, Object... params)
  9. invokeMethodOnObject(Method method, Object objectToInvokeOn, Object[] args)