Example usage for java.lang.reflect Method getName

List of usage examples for java.lang.reflect Method getName

Introduction

In this page you can find the example usage for java.lang.reflect Method getName.

Prototype

@Override
public String getName() 

Source Link

Document

Returns the name of the method represented by this Method object, as a String .

Usage

From source file:io.github.wysohn.triggerreactor.tools.ReflectionUtil.java

@SuppressWarnings({ "unchecked", "unchecked" })
public static Object invokeMethod(Class<?> clazz, Object obj, String methodName, Object... args)
        throws NoSuchMethodException, IllegalArgumentException, InvocationTargetException,
        IllegalAccessException {/*from  w  w w  .j a va  2s .  co  m*/
    try {
        List<Method> validMethods = new ArrayList<>();

        for (Method method : clazz.getMethods()) {
            Class<?>[] parameterTypes = null;

            if (!method.getName().equals(methodName)) {
                continue;
            }

            parameterTypes = method.getParameterTypes();
            if (method.isVarArgs()) {
                if (method.isVarArgs() && (parameterTypes.length - args.length >= 2)) {
                    parameterTypes = null;
                    continue;
                }
            } else {
                if (parameterTypes.length != args.length) {
                    parameterTypes = null;
                    continue;
                }
            }

            if (method.isVarArgs()) {
                boolean matches = false;

                // check non vararg part
                for (int i = 0; i < parameterTypes.length - 1; i++) {
                    matches = checkMatch(parameterTypes[i], args[i]);
                    if (!matches)
                        break;
                }

                // check rest
                for (int i = parameterTypes.length - 1; i < args.length; i++) {
                    Class<?> arrayType = parameterTypes[parameterTypes.length - 1].getComponentType();

                    matches = checkMatch(arrayType, args[i]);
                    if (!matches)
                        break;
                }

                if (matches) {
                    validMethods.add(method);
                }
            } else {
                boolean matches = true;

                for (int i = 0; i < parameterTypes.length; i++) {
                    matches = checkMatch(parameterTypes[i], args[i]);
                    if (!matches)
                        break;
                }

                if (matches) {
                    validMethods.add(method);
                }
            }
        }

        if (!validMethods.isEmpty()) {
            Method method = validMethods.get(0);
            for (int i = 1; i < validMethods.size(); i++) {
                Method targetMethod = validMethods.get(i);

                Class<?>[] currentParams = method.getParameterTypes();
                Class<?>[] targetParams = targetMethod.getParameterTypes();

                if (method.isVarArgs() && targetMethod.isVarArgs()) {
                    for (int j = 0; j < currentParams.length; j++) {
                        if (currentParams[j].isAssignableFrom(targetParams[j])) {
                            method = targetMethod;
                            break;
                        }
                    }
                } else if (method.isVarArgs()) {
                    //usually, non-vararg is more specific method. So we use that
                    method = targetMethod;
                } else if (targetMethod.isVarArgs()) {
                    //do nothing
                } else {
                    for (int j = 0; j < currentParams.length; j++) {
                        if (targetParams[j].isEnum()) { // enum will be handled later
                            method = targetMethod;
                            break;
                        } else if (ClassUtils.isAssignable(targetParams[j], currentParams[j], true)) { //narrow down to find the most specific method
                            method = targetMethod;
                            break;
                        }
                    }
                }
            }

            method.setAccessible(true);

            for (int i = 0; i < args.length; i++) {
                Class<?>[] parameterTypes = method.getParameterTypes();

                if (args[i] instanceof String && i < parameterTypes.length && parameterTypes[i].isEnum()) {
                    try {
                        args[i] = Enum.valueOf((Class<? extends Enum>) parameterTypes[i], (String) args[i]);
                    } catch (IllegalArgumentException ex1) {
                        // Some overloaded methods already has
                        // String to Enum conversion
                        // So just lets see if one exists
                        Class<?>[] types = new Class<?>[args.length];
                        for (int k = 0; k < args.length; k++)
                            types[k] = args[k].getClass();

                        try {
                            Method alternative = clazz.getMethod(methodName, types);
                            return alternative.invoke(obj, args);
                        } catch (NoSuchMethodException ex2) {
                            throw new RuntimeException(
                                    "Tried to convert value [" + args[i] + "] to Enum [" + parameterTypes[i]
                                            + "] or find appropriate method but found nothing. Make sure"
                                            + " that the value [" + args[i]
                                            + "] matches exactly with one of the Enums in [" + parameterTypes[i]
                                            + "] or the method you are looking exists.");
                        }
                    }
                }
            }

            if (method.isVarArgs()) {
                Class<?>[] parameterTypes = method.getParameterTypes();

                Object varargs = Array.newInstance(parameterTypes[parameterTypes.length - 1].getComponentType(),
                        args.length - parameterTypes.length + 1);
                for (int k = 0; k < Array.getLength(varargs); k++) {
                    Array.set(varargs, k, args[parameterTypes.length - 1 + k]);
                }

                Object[] newArgs = new Object[parameterTypes.length];
                for (int k = 0; k < newArgs.length - 1; k++) {
                    newArgs[k] = args[k];
                }
                newArgs[newArgs.length - 1] = varargs;

                args = newArgs;
            }

            return method.invoke(obj, args);
        }

        if (args.length > 0) {
            StringBuilder builder = new StringBuilder(String.valueOf(args[0].getClass().getSimpleName()));

            for (int i = 1; i < args.length; i++) {
                builder.append(", " + args[i].getClass().getSimpleName());
            }

            throw new NoSuchMethodException(methodName + "(" + builder.toString() + ")");
        } else {
            throw new NoSuchMethodException(methodName + "()");
        }
    } catch (NullPointerException e) {
        StringBuilder builder = new StringBuilder(String.valueOf(args[0]));
        for (int i = 1; i < args.length; i++)
            builder.append("," + String.valueOf(args[i]));
        throw new NullPointerException("Call " + methodName + "(" + builder.toString() + ")");
    }
}

From source file:com.amazonaws.services.simpleworkflow.flow.common.WorkflowExecutionUtils.java

/**
 * Not really a generic method for printing random object graphs. But it
 * works for events and decisions./* w w w. j  av a 2 s .  c om*/
 */
private static String prettyPrintObject(Object object, String methodToSkip,
        boolean skipNullsAndEmptyCollections, String indentation, boolean skipLevel) {
    StringBuffer result = new StringBuffer();
    if (object == null) {
        return "null";
    }
    Class<? extends Object> clz = object.getClass();
    if (Number.class.isAssignableFrom(clz)) {
        return String.valueOf(object);
    }
    if (Boolean.class.isAssignableFrom(clz)) {
        return String.valueOf(object);
    }
    if (clz.equals(String.class)) {
        return (String) object;
    }
    if (clz.equals(Date.class)) {
        return String.valueOf(object);
    }
    if (Map.class.isAssignableFrom(clz)) {
        return String.valueOf(object);
    }
    if (Collection.class.isAssignableFrom(clz)) {
        return String.valueOf(object);
    }
    if (!skipLevel) {
        result.append(" {");
    }
    Method[] eventMethods = object.getClass().getMethods();
    boolean first = true;
    for (Method method : eventMethods) {
        String name = method.getName();
        if (!name.startsWith("get")) {
            continue;
        }
        if (name.equals(methodToSkip) || name.equals("getClass")) {
            continue;
        }
        if (Modifier.isStatic(method.getModifiers())) {
            continue;
        }
        Object value;
        try {
            value = method.invoke(object, (Object[]) null);
            if (value != null && value.getClass().equals(String.class) && name.equals("getDetails")) {
                value = printDetails((String) value);
            }
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e.getTargetException());
        } catch (RuntimeException e) {
            throw (RuntimeException) e;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (skipNullsAndEmptyCollections) {
            if (value == null) {
                continue;
            }
            if (value instanceof Map && ((Map<?, ?>) value).isEmpty()) {
                continue;
            }
            if (value instanceof Collection && ((Collection<?>) value).isEmpty()) {
                continue;
            }
        }
        if (!skipLevel) {
            if (first) {
                first = false;
            } else {
                result.append(";");
            }
            result.append("\n");
            result.append(indentation);
            result.append("    ");
            result.append(name.substring(3));
            result.append(" = ");
            result.append(prettyPrintObject(value, methodToSkip, skipNullsAndEmptyCollections,
                    indentation + "    ", false));
        } else {
            result.append(
                    prettyPrintObject(value, methodToSkip, skipNullsAndEmptyCollections, indentation, false));
        }
    }
    if (!skipLevel) {
        result.append("\n");
        result.append(indentation);
        result.append("}");
    }
    return result.toString();
}

From source file:io.servicecomb.swagger.generator.core.utils.ParamUtils.java

public static void setParameterType(Swagger swagger, Method method, int paramIdx,
        AbstractSerializableParameter<?> parameter) {
    Type paramType = ParamUtils.getGenericParameterType(method, paramIdx);

    ParamUtils.addDefinitions(swagger, paramType);

    Property property = ModelConverters.getInstance().readAsProperty(paramType);

    if (isComplexProperty(property)) {
        // ??????
        String msg = String.format(
                "not allow complex type for %s parameter, method=%s:%s, paramIdx=%d, type=%s",
                parameter.getIn(), method.getDeclaringClass().getName(), method.getName(), paramIdx,
                paramType.getTypeName());
        throw new Error(msg);
    }//w  w  w. j a v  a  2  s .c  om
    parameter.setProperty(property);
}

From source file:com.lucidtechnics.blackboard.TargetConstructor.java

private final static void printMethods(Class _class) {
    List methodList = new ArrayList();

    Enhancer.getMethods(_class, null, methodList);

    Predicate mutatorPredicate = new Predicate() {
        public boolean evaluate(Object _object) {
            Method method = (Method) _object;

            if (logger.isDebugEnabled() == true) {
                logger.debug("Printing out specifics for method: " + method.getName() + " with return type: "
                        + method.getReturnType().getName());
            }/*from w  ww.ja v a 2 s . c  o  m*/

            for (int i = 0; i < method.getParameterTypes().length; i++) {
                if (logger.isDebugEnabled() == true) {
                    logger.debug("and with parameter type: " + method.getParameterTypes()[i]);
                }
            }

            return true;
        }
    };

    CollectionUtils.filter(methodList, mutatorPredicate);
}

From source file:bammerbom.ultimatecore.bukkit.resources.utils.BossbarUtil.java

public static Method getMethod(Class<?> cl, String method) {
    for (Method m : cl.getMethods()) {
        if (m.getName().equals(method)) {
            return m;
        }//from  w w w. j  a va  2s  .c  o m
    }
    return null;
}

From source file:bammerbom.ultimatecore.bukkit.resources.utils.BossbarUtil.java

public static Method getMethod(Class<?> cl, String method, Class<?>[] args) {
    for (Method m : cl.getMethods()) {
        if ((m.getName().equals(method)) && (ClassListEqual(args, m.getParameterTypes()))) {
            return m;
        }//w w w  . j  av a2  s. c  om
    }
    return null;
}

From source file:bammerbom.ultimatecore.bukkit.resources.utils.BossbarUtil.java

public static Method getMethod(Class<?> cl, String method, Integer args) {
    for (Method m : cl.getMethods()) {
        if ((m.getName().equals(method)) && (args.equals(new Integer(m.getParameterTypes().length)))) {
            return m;
        }//w  ww  .j a  v a 2  s  .c om
    }
    return null;
}

From source file:br.com.lucasisrael.regra.reflections.TratamentoReflections.java

/**
 * Attempt to find a {@link Method} on the supplied class with the supplied name
 * and parameter types. Searches all superclasses up to {@code Object}.
 * <p>Returns {@code null} if no {@link Method} can be found.
 * @param clazz the class to introspect//from  w  ww  .j av a 2s .co m
 * @param name the name of the method
 * @param paramTypes the parameter types of the method
 * (may be {@code null} to indicate any signature)
 * @return the Method object, or {@code null} if none found
 */
public static Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes) {
    Assert.notNull(clazz, "Class must not be null");
    Assert.notNull(name, "Method name must not be null");
    Class<?> searchType = clazz;
    while (searchType != null) {
        Method[] methods = (searchType.isInterface() ? searchType.getMethods()
                : searchType.getDeclaredMethods());
        for (Method method : methods) {
            if (name.equals(method.getName())
                    && (paramTypes == null || Arrays.equals(paramTypes, method.getParameterTypes()))) {
                return method;
            }
        }
        searchType = searchType.getSuperclass();
    }
    return null;
}

From source file:com.xiongyingqi.util.ReflectionUtils.java

/**
 * Determine whether the given method is originally declared by {@link Object}.
 *//*from  w  ww  .j a v a 2 s . co m*/
public static boolean isObjectMethod(Method method) {
    try {
        Object.class.getDeclaredMethod(method.getName(), method.getParameterTypes());
        return true;
    } catch (SecurityException ex) {
        return false;
    } catch (NoSuchMethodException ex) {
        return false;
    }
}

From source file:br.com.lucasisrael.regra.reflections.TratamentoReflections.java

/**
 * Determine whether the given method is a CGLIB 'renamed' method,
 * following the pattern "CGLIB$methodName$0".
 * @param renamedMethod the method to check
 * @see org.springframework.cglib.proxy.Enhancer#rename
 *//*ww w. j a v  a 2s .co m*/
public static boolean isCglibRenamedMethod(Method renamedMethod) {
    return CGLIB_RENAMED_METHOD_PATTERN.matcher(renamedMethod.getName()).matches();
}