Example usage for java.lang.reflect Method toGenericString

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

Introduction

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

Prototype

@Override
public String toGenericString() 

Source Link

Document

Returns a string describing this Method , including type parameters.

Usage

From source file:org.springframework.core.GenericTypeResolver.java

/**
 * Determine the target type for the generic return type of the given
 * <em>generic method</em>, where formal type variables are declared on
 * the given method itself./*from   www. ja va  2  s  .co m*/
 *
 * <p>For example, given a factory method with the following signature,
 * if {@code resolveReturnTypeForGenericMethod()} is invoked with the reflected
 * method for {@code creatProxy()} and an {@code Object[]} array containing
 * {@code MyService.class}, {@code resolveReturnTypeForGenericMethod()} will
 * infer that the target return type is {@code MyService}.
 *
 * <pre>{@code public static <T> T createProxy(Class<T> clazz)}</pre>
 *
 * <h4>Possible Return Values</h4>
 * <ul>
 * <li>the target return type, if it can be inferred</li>
 * <li>the {@linkplain Method#getReturnType() standard return type}, if
 * the given {@code method} does not declare any {@linkplain
 * Method#getTypeParameters() formal type variables}</li>
 * <li>the {@linkplain Method#getReturnType() standard return type}, if the
 * target return type cannot be inferred (e.g., due to type erasure)</li>
 * <li>{@code null}, if the length of the given arguments array is shorter
 * than the length of the {@linkplain
 * Method#getGenericParameterTypes() formal argument list} for the given
 * method</li>
 * </ul>
 *
 * @param method the method to introspect, never {@code null}
 * @param args the arguments that will be supplied to the method when it is
 * invoked, never {@code null}
 * @return the resolved target return type, the standard return type, or
 * {@code null}
 * @since 3.2
 * @see #resolveReturnType
 */
public static Class<?> resolveReturnTypeForGenericMethod(Method method, Object[] args) {
    Assert.notNull(method, "method must not be null");
    Assert.notNull(args, "args must not be null");

    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Resolving return type for [%s] with concrete method arguments [%s].",
                method.toGenericString(), ObjectUtils.nullSafeToString(args)));
    }

    final TypeVariable<Method>[] declaredTypeVariables = method.getTypeParameters();
    final Type genericReturnType = method.getGenericReturnType();
    final Type[] methodArgumentTypes = method.getGenericParameterTypes();

    // No declared type variables to inspect, so just return the standard return type.
    if (declaredTypeVariables.length == 0) {
        return method.getReturnType();
    }

    // The supplied argument list is too short for the method's signature, so
    // return null, since such a method invocation would fail.
    if (args.length < methodArgumentTypes.length) {
        return null;
    }

    // Ensure that the type variable (e.g., T) is declared directly on the method
    // itself (e.g., via <T>), not on the enclosing class or interface.
    boolean locallyDeclaredTypeVariableMatchesReturnType = false;
    for (TypeVariable<Method> currentTypeVariable : declaredTypeVariables) {
        if (currentTypeVariable.equals(genericReturnType)) {
            if (logger.isDebugEnabled()) {
                logger.debug(String.format(
                        "Found declared type variable [%s] that matches the target return type [%s].",
                        currentTypeVariable, genericReturnType));
            }
            locallyDeclaredTypeVariableMatchesReturnType = true;
            break;
        }
    }

    if (locallyDeclaredTypeVariableMatchesReturnType) {
        for (int i = 0; i < methodArgumentTypes.length; i++) {
            final Type currentMethodArgumentType = methodArgumentTypes[i];

            if (currentMethodArgumentType.equals(genericReturnType)) {
                if (logger.isDebugEnabled()) {
                    logger.debug(String.format(
                            "Found method argument type at index [%s] that matches the target return type.",
                            i));
                }
                return args[i].getClass();
            }

            if (currentMethodArgumentType instanceof ParameterizedType) {
                ParameterizedType parameterizedType = (ParameterizedType) currentMethodArgumentType;
                Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();

                for (int j = 0; j < actualTypeArguments.length; j++) {
                    final Type typeArg = actualTypeArguments[j];

                    if (typeArg.equals(genericReturnType)) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(String.format(
                                    "Found method argument type at index [%s] that is parameterized with a type argument that matches the target return type.",
                                    i));
                        }

                        if (args[i] instanceof Class) {
                            return (Class<?>) args[i];
                        } else {
                            // Consider adding logic to determine the class of the
                            // J'th typeArg, if possible.
                            logger.info(String.format(
                                    "Could not determine the target type for type argument [%s] for method [%s].",
                                    typeArg, method.toGenericString()));

                            // For now, just fall back...
                            return method.getReturnType();
                        }
                    }
                }
            }
        }
    }

    // Fall back...
    return method.getReturnType();
}

From source file:com.just.agentweb.AgentWebUtils.java

static boolean isOverriedMethod(Object currentObject, String methodName, String method, Class... clazzs) {
    LogUtils.i(TAG, "  methodName:" + methodName + "   method:" + method);
    boolean tag = false;
    if (currentObject == null) {
        return tag;
    }//  ww w . j  av  a 2 s .c  om
    try {
        Class clazz = currentObject.getClass();
        Method mMethod = clazz.getMethod(methodName, clazzs);
        String gStr = mMethod.toGenericString();
        tag = !gStr.contains(method);
    } catch (Exception igonre) {
        if (LogUtils.isDebug()) {
            igonre.printStackTrace();
        }
    }

    LogUtils.i(TAG, "isOverriedMethod:" + tag);
    return tag;
}

From source file:org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.java

private static String getMethodRequestMapping(Method method) {
    Assert.notNull(method, "'method' must not be null");
    RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class);
    if (requestMapping == null) {
        throw new IllegalArgumentException("No @RequestMapping on: " + method.toGenericString());
    }//from  w  w w.j a  va  2s  . co  m
    String[] paths = requestMapping.path();
    if (ObjectUtils.isEmpty(paths) || StringUtils.isEmpty(paths[0])) {
        return "/";
    }
    if (paths.length > 1 && logger.isWarnEnabled()) {
        logger.warn("Multiple paths on method " + method.toGenericString() + ", using first one");
    }
    return paths[0];
}

From source file:com.smhumayun.mi_plus.impl.MIMethodResolverImpl.java

/**
 * Resolve method based on following strategy:
 * - Iterate over composed objects (order will be the same as defined in {@link com.smhumayun.mi_plus.MISupport}
 * - For each composed object, check if there's a matching 'accessible' method based on the algorithm defined by
 * {@link MethodUtils#getAccessibleMethod(Class, String, Class[])} i.e. it finds an accessible method that matches
 * the given name and has compatible parameters. Compatible parameters mean that every method parameter is
 * assignable from the given parameters. In other words, it finds a method with the given name that will take the
 * parameters given.//from  w w w .  j ava  2s .c om
 * - If a match is found, break the iteration and exit from the loop;
 * - Return the corresponding composed object and the matched method
 *
 * @param miContainerClass      MI Container class
 * @param composedObjects       map of composed objects
 * @param methodCall            method call made on Proxy
 * @param methodCallArgs        method call arguments
 * @return resolved target method and object
 * @throws com.smhumayun.mi_plus.MIException {@link com.smhumayun.mi_plus.MIException}
 */
public Pair<Object, Method> resolve(Class miContainerClass, LinkedHashMap<Class, Object> composedObjects,
        Method methodCall, Object[] methodCallArgs) throws MIException {
    logger.info("resolve " + methodCall.toGenericString());
    Class[] methodCallArgsClasses = utils.getClasses(methodCallArgs);
    logger.fine("methodCallArgs classes = " + Arrays.toString(methodCallArgsClasses));
    Object targetObject = null;
    Method targetMethod = null;
    for (Class composedObjectClass : composedObjects.keySet()) {
        try {
            targetMethod = MethodUtils.getMatchingAccessibleMethod(composedObjectClass, methodCall.getName(),
                    methodCallArgsClasses);
            if (targetMethod != null) {
                logger.info("matching method found! " + targetMethod.toGenericString());
                targetObject = composedObjects.get(composedObjectClass);
                break;
            }
        } catch (Exception e) {
            /* SWALLOW */ }
    }
    //if not found
    if (targetMethod == null)
        //throw exception
        throw new UnsupportedOperationException("method '" + methodCall.toGenericString() + "' not found");
    //else return the target object and method to caller
    return new Pair<Object, Method>(targetObject, targetMethod);
}

From source file:com.wickettraining.modelproxy.ProxyManager.java

protected String createUniqueID(Object object, Method method) {
    return createUniqueID(object) + "--" + method.toGenericString();
}

From source file:com.hubspot.utils.circuitbreaker.CircuitBreakerInvocationHandler.java

/**
 *  Called from a Proxy instance to invoke a method on the realObj stored by this handler.
 *  /*  www  .j ava 2s  . c  o  m*/
 *  If a "blacklisted" exception is thrown, we inform our CircuitBreakerPolicy let it
 *  tell us whether we should move states.
 */
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    getLog().debug("circuit breaker wrapped method invocation = " + method.toGenericString());

    Throwable fromInvocation = null;
    Object ret = null;
    try {
        if (blacklist.containsKey(method) && policy.getCurrentState() == CircuitBreakerState.OPEN
                && !policy.shouldAttemptReset()) {
            // breaker is open, just throw our standard CircuitBreakerException
            throw new CircuitBreakerException();
        }

        // circuit breaker is either open or half-open, do our invocation
        ret = method.invoke(realObj, args);
    } catch (InvocationTargetException e) {
        // The underlying method was called successfully, but threw an exception.
        // we want to pass that exception on.
        fromInvocation = e.getCause();
    } catch (IllegalArgumentException e) {
        // "In a properly constructed proxy, this should never happen."
        getLog().debug("Illegal argument exception in circuit breaker handler" + e);
        throw e;

    } catch (IllegalAccessException e) {
        // "In a properly constructed proxy, this should never happen."
        getLog().debug("Illegal access exception in circuit breaker handler" + e);
        throw e;
    }

    // exception was thrown, determine if it was blacklisted and if we should trip
    if (fromInvocation != null) {
        if (blacklist.containsKey(method)) {
            Class[] blacklistedExceptionTypes = blacklist.get(method);
            if (ArrayUtils.contains(blacklistedExceptionTypes, fromInvocation.getClass())) {
                policy.failedBlacklistedCall(method);
            }
        } else {
            policy.successfulCall(method);
        }
        throw fromInvocation;
    }

    if (blacklist.containsKey(method))
        policy.successfulCall(method);

    return ret;
}

From source file:org.hawkular.rest.interceptors.LoggingInterceptor.java

@Override
public void filter(ContainerRequestContext containerRequestContext) throws IOException {
    if (REQUESTS_LOGGER.isDebugEnabled()) {
        final String method = containerRequestContext.getMethod();
        final String url = containerRequestContext.getUriInfo().getRequestUri().toString();
        final StringBuilder headersStr = new StringBuilder();
        MultivaluedMap<String, String> headers = containerRequestContext.getHeaders();
        for (MultivaluedMap.Entry<String, List<String>> header : headers.entrySet()) {
            headersStr.append(header.getKey()).append(": ").append(header.getValue()).append('\n');
        }/* w w w . ja v a 2  s .  c o  m*/

        String json = null;
        if ("POST".equals(method) || "PUT".equals(method)) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IOUtils.copy(containerRequestContext.getEntityStream(), baos);
            byte[] jsonBytes = baos.toByteArray();
            json = new String(jsonBytes, "UTF-8");
            Object jsonObject = MAPPER.readValue(json, Object.class);
            json = MAPPER.writeValueAsString(jsonObject);
            containerRequestContext.setEntityStream(new ByteArrayInputStream(jsonBytes));
        }
        PostMatchContainerRequestContext pmContext = (PostMatchContainerRequestContext) containerRequestContext;
        // this should be safe, because if some calling non-existent api the javax.ws.rs.NotFoundException should
        // be already thrown and this interceptor isn't triggered
        Method javaMethod = pmContext.getResourceMethod().getMethod();
        REQUESTS_LOGGER.restCall(method, url, headersStr.toString(), json == null ? "empty" : json,
                javaMethod.toGenericString());
    }
}

From source file:org.midonet.config.ConfigProvider.java

private static Object handleInvocation(Method method, Object[] args, ConfigProvider provider) {

    ConfigInt integerConfigAnn = method.getAnnotation(ConfigInt.class);
    if (integerConfigAnn != null) {
        return provider.getValue(findDeclaredGroupName(method), integerConfigAnn.key(),
                integerConfigAnn.defaultValue());
    }//from   w ww  .  ja va  2 s .co  m

    ConfigLong longConfigAnn = method.getAnnotation(ConfigLong.class);
    if (longConfigAnn != null) {
        return provider.getValue(findDeclaredGroupName(method), longConfigAnn.key(),
                longConfigAnn.defaultValue());
    }

    ConfigBool boolConfigAnn = method.getAnnotation(ConfigBool.class);
    if (boolConfigAnn != null) {
        return provider.getValue(findDeclaredGroupName(method), boolConfigAnn.key(),
                boolConfigAnn.defaultValue());
    }

    ConfigString strConfigAnn = method.getAnnotation(ConfigString.class);
    if (strConfigAnn != null) {
        return provider.getValue(findDeclaredGroupName(method), strConfigAnn.key(),
                strConfigAnn.defaultValue());
    }

    throw new IllegalArgumentException("Method " + method.toGenericString() + " is being used as an "
            + "config entry accessor but is not annotated with one of the"
            + "@ConfigInt, @ConfigLong, @ConfigString, @ConfigBool " + "annotations.");
}

From source file:org.alfresco.traitextender.AJExtender.java

/**
 * @param extensible//  w w w  .ja v a2 s  . c om
 * @return a compilation result containing all {@link Extend} mapped routes,
 *         not routed or dangling methods within the give extensible class.
 * @throws AJExtensibleCompilingException
 */
static CompiledExtensible compile(Class<? extends Extensible> extensible)
        throws AJExtensibleCompilingException {
    logger.info("Compiling extensible " + extensible);

    CompiledExtensible compiledExtensible = new CompiledExtensible(extensible);

    List<Method> methods = new ArrayList<>();
    Class<?> extendDeclaring = extensible;
    while (extendDeclaring != null) {
        Method[] declaredMethods = extendDeclaring.getDeclaredMethods();
        methods.addAll(Arrays.asList(declaredMethods));
        extendDeclaring = extendDeclaring.getSuperclass();
    }
    Set<Extend> extendDeclarations = new HashSet<>();
    Set<Method> routedExtensionMethods = new HashSet<>();
    for (Method method : methods) {

        Extend extend = method.getAnnotation(Extend.class);
        if (extend != null) {
            try {
                extendDeclarations.add(extend);
                Class<?> extensionAPI = extend.extensionAPI();
                Method extensionMethod = extensionAPI.getMethod(method.getName(), method.getParameterTypes());
                compiledExtensible.add(new ExtensionRoute(extend, method, extensionMethod));
                routedExtensionMethods.add(extensionMethod);
            } catch (NoSuchMethodException error) {
                AJExtensibleCompilingException ajCompilingError = new AJExtensibleCompilingException(
                        "No route for " + method.toGenericString() + " @" + extend, error);
                compiledExtensible.add(ajCompilingError);
            } catch (SecurityException error) {
                AJExtensibleCompilingException ajCompilingError = new AJExtensibleCompilingException(
                        "Access denined to route for " + method.toGenericString() + " @" + extend, error);
                compiledExtensible.add(ajCompilingError);
            }
        }

    }

    final Set<Method> allObjectMethods = new HashSet<>(Arrays.asList(Object.class.getMethods()));

    for (Extend extend : extendDeclarations) {
        Class<?> extension = extend.extensionAPI();

        Set<Method> allExtensionMethods = new HashSet<>(Arrays.asList(extension.getMethods()));
        allExtensionMethods.removeAll(allObjectMethods);
        allExtensionMethods.removeAll(routedExtensionMethods);
        if (!allExtensionMethods.isEmpty()) {
            for (Method method : allExtensionMethods) {
                compiledExtensible.add(new AJDanglingExtensionError(method, extend));
            }
        }
    }

    logger.info(compiledExtensible.getInfo());

    return compiledExtensible;
}

From source file:candr.yoclip.option.OptionPropertiesSetter.java

/**
 * Initializes the method descriptor to create an association between the bean setter {@code Method} and the
 * {@code OptionProperties} annotation./*from  w ww.  j a  va2s  .  c  o m*/
 *
 * @param optionProperties The annotation associated with the bean setter.
 * @param setter           The bean setter method annotated with {@code OptionProperties}.
 * @throws OptionsBadTypeException if the setter is not assignable to the Java {@code Map} interface.
 * @throws OptionsBadNameException if the {@link OptionProperties#name() name} is empty.
 */
protected OptionPropertiesSetter(final OptionProperties optionProperties, final Method setter) {

    super(setter);

    final Class<?>[] parameterTypes = setter.getParameterTypes();
    if (2 != parameterTypes.length) {
        throw new UnsupportedOperationException(setter.toGenericString() + " must have 2 parameters.");
    }
    if (!String.class.isAssignableFrom(parameterTypes[0])
            || !String.class.isAssignableFrom(parameterTypes[1])) {
        throw new IllegalArgumentException(setter.toGenericString() + " parameters must both be String");
    }
    if (StringUtils.isEmpty(optionProperties.name())) {
        throw new OptionsBadNameException(setter.getName() + " option name is empty.");
    }

    this.optionProperties = optionProperties;
}