Example usage for java.lang.reflect Method isBridge

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

Introduction

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

Prototype

public boolean isBridge() 

Source Link

Document

Returns true if this method is a bridge method; returns false otherwise.

Usage

From source file:org.evosuite.testcase.statements.FunctionalMockStatement.java

public static boolean canBeFunctionalMocked(Type type) {

    Class<?> rawClass = new GenericClass(type).getRawClass();
    final Class<?> targetClass = Properties.getTargetClassAndDontInitialise();

    if (Properties.hasTargetClassBeenLoaded() && (rawClass.equals(targetClass))) {
        return false;
    }/*  ww  w .j a  va 2s  .  c o  m*/

    if (EvoSuiteMock.class.isAssignableFrom(rawClass) || MockList.isAMockClass(rawClass.getName())
            || rawClass.equals(Class.class) || rawClass.isArray() || rawClass.isPrimitive()
            || rawClass.isAnonymousClass() || rawClass.isEnum() ||
            //note: Mockito can handle package-level classes, but we get all kinds of weird exceptions with instrumentation :(
            !Modifier.isPublic(rawClass.getModifiers())) {
        return false;
    }

    if (!InstrumentedClass.class.isAssignableFrom(rawClass) && Modifier.isFinal(rawClass.getModifiers())) {
        /*
        if a class has not been instrumented (eg because belonging to javax.*),
        then if it is final we cannot mock it :(
        recall that instrumentation does remove the final modifiers
         */
        return false;
    }

    //FIXME: tmp fix to avoid mocking any class with package access methods
    try {
        for (Method m : rawClass.getDeclaredMethods()) {

            /*
            Unfortunately, it does not seem there is a "isPackageLevel" method, so we have
            to go by exclusion
             */

            if (!Modifier.isPublic(m.getModifiers()) && !Modifier.isProtected(m.getModifiers())
                    && !Modifier.isPrivate(m.getModifiers()) && !m.isBridge() && !m.isSynthetic()
                    && !m.getName().equals(ClassResetter.STATIC_RESET)) {
                return false;
            }
        }
    } catch (NoClassDefFoundError | Exception e) {
        //this could happen if we failed to load the class
        AtMostOnceLogger.warn(logger,
                "Failed to check if can mock class " + rawClass.getName() + ": " + e.getMessage());
        return false;
    }

    //avoid cases of infinite recursions
    boolean onlySelfReturns = true;
    for (Method m : rawClass.getDeclaredMethods()) {
        if (!rawClass.equals(m.getReturnType())) {
            onlySelfReturns = false;
            break;
        }
    }

    if (onlySelfReturns && rawClass.getDeclaredMethods().length > 0) {
        //avoid weird cases like java.lang.Appendable
        return false;
    }

    //ad-hoc list of classes we should not really mock
    List<Class<?>> avoid = Arrays.asList(
    //add here if needed
    );

    if (avoid.contains(rawClass)) {
        return false;
    }

    return true;
}

From source file:org.grouplens.lenskit.data.text.Fields.java

/**
 * Get a field by name.  It first looks up the common fields, and if none of them apply, creates
 * a reflection-based field.//  ww w.  j  av  a2s  .c o  m
 *
 * @param eb The event builder.
 * @param name The field name.  The name can be suffixed with "?" to make it optional.
 * @return The field, or `null` if no such field can be defined.
 */
public static Field byName(Class<? extends EventBuilder> eb, String name) {
    Field field = commonField(name);
    if (field != null) {
        return field;
    }

    boolean optional = false;
    if (name.endsWith("?")) {
        optional = true;
        name = name.substring(0, name.length() - 1);
    }

    String setterName = "set" + StringUtils.capitalize(name);
    Method setter = null;
    Method annotated = null;
    for (Method m : eb.getMethods()) {
        FieldName nameAnnot = m.getAnnotation(FieldName.class);
        if (nameAnnot != null) {
            if (nameAnnot.value().equals(name)) {
                annotated = m;
            }
        } else if (m.getName().equals(setterName) && !m.isBridge()) {
            if (setter == null) {
                setter = m;
            } else {
                throw new IllegalArgumentException("Multiple methods named " + setterName);
            }
        }
    }
    if (annotated != null) {
        setter = annotated;
    }

    if (setter == null) {
        throw new IllegalArgumentException("No method found for field " + name);
    }
    Class<?>[] atypes = setter.getParameterTypes();
    if (atypes.length != 1) {
        throw new IllegalArgumentException("Method " + setter.getName() + " takes too many arguments");
    }
    final Method theSetter = setter;
    Class<?> atype = atypes[0];
    if (atype.isPrimitive()) {
        atype = ClassUtils.primitiveToWrapper(atype);
    }
    StringConverter<Object> convert = StringConvert.INSTANCE.findConverterNoGenerics(atype);
    if (convert == null) {
        throw new IllegalArgumentException("Field type " + atypes[0] + " not allowed.");
    }
    return new ReflectionField(name, theSetter, eb, atype, convert, optional);
}

From source file:org.hopen.framework.rewrite.GenericTypeAwarePropertyDescriptor.java

public GenericTypeAwarePropertyDescriptor(Class beanClass, String propertyName, Method readMethod,
        Method writeMethod, Class propertyEditorClass) throws IntrospectionException {

    super(propertyName, null, null);
    this.beanClass = beanClass;
    this.propertyEditorClass = propertyEditorClass;

    Method readMethodToUse = BridgeMethodResolver.findBridgedMethod(readMethod);
    Method writeMethodToUse = BridgeMethodResolver.findBridgedMethod(writeMethod);
    if (writeMethodToUse == null && readMethodToUse != null) {
        // Fallback: Original JavaBeans introspection might not have found matching setter
        // method due to lack of bridge method resolution, in case of the getter using a
        // covariant return type whereas the setter is defined for the concrete property type.
        writeMethodToUse = ClassUtils.getMethodIfAvailable(this.beanClass,
                "set" + StringUtils.capitalize(getName()), readMethodToUse.getReturnType());
    }//  w ww  .  j  a  v a2 s  . com
    this.readMethod = readMethodToUse;
    this.writeMethod = writeMethodToUse;

    if (this.writeMethod != null && this.readMethod == null) {
        // Write method not matched against read method: potentially ambiguous through
        // several overloaded variants, in which case an arbitrary winner has been chosen
        // by the JDK's JavaBeans Introspector...
        Set<Method> ambiguousCandidates = new HashSet<Method>();
        for (Method method : beanClass.getMethods()) {
            if (method.getName().equals(writeMethodToUse.getName()) && !method.equals(writeMethodToUse)
                    && !method.isBridge()) {
                ambiguousCandidates.add(method);
            }
        }
        if (!ambiguousCandidates.isEmpty()) {
            this.ambiguousWriteMethods = ambiguousCandidates;
        }
    }
}

From source file:org.jtester.utility.ReflectionUtils.java

/**
 * Gets all methods of the given class and all its super-classes.
 * /*from  w  w  w .j a  v  a  2  s  .c  om*/
 * @param clazz
 *            The class
 * @return The methods, not null
 */
public static Set<Method> getAllMethods(Class<?> clazz) {
    Set<Method> result = new HashSet<Method>();
    if (clazz == null || clazz.equals(Object.class)) {
        return result;
    }

    // add all methods of this class
    Method[] declaredMethods = clazz.getDeclaredMethods();
    for (Method declaredMethod : declaredMethods) {
        if (declaredMethod.isSynthetic() || declaredMethod.isBridge()) {
            // skip methods that were added by the compiler
            continue;
        }
        result.add(declaredMethod);
    }
    // add all methods of the super-classes
    result.addAll(getAllMethods(clazz.getSuperclass()));
    return result;
}

From source file:org.lunarray.model.descriptor.util.ReflectionUtil.java

/**
 * Gets all methods in a type, using tail recursion.
 * //from   ww w.  j  a v a2  s .c o m
 * @param methods
 *            The tail. May not be null.
 * @param type
 *            The type. May not be null.
 * @param findStatic
 *            Set to true to find static methods, otherwise, only none
 *            static.
 * @param excludeJavaLang
 *            Whether or not to exclude methods from java.lang.*.
 */
public static void getMethods(final List<Method> methods, final Class<?> type, final boolean findStatic,
        final boolean excludeJavaLang) {
    Validate.notNull(methods, ReflectionUtil.TAIL_NULL);
    Validate.notNull(type, ReflectionUtil.TYPE_NULL);
    for (final Method method : type.getMethods()) {
        if ((findStatic == Modifier.isStatic(method.getModifiers())) && !method.isBridge() && ReflectionUtil
                .testPackage(method.getDeclaringClass(), ReflectionUtil.JAVA_LANG, excludeJavaLang)) {
            methods.add(method);
        }
    }
    final Class<?> superClass = type.getSuperclass();
    if (!CheckUtil.isNull(superClass)) {
        final String packageName = superClass.getPackage().getName();
        if (excludeJavaLang != ReflectionUtil.JAVA_LANG.equals(packageName)) {
            ReflectionUtil.getMethods(methods, superClass, findStatic, excludeJavaLang);
        }
    }
}

From source file:org.projectforge.common.BeanHelper.java

public static Method determineGetter(final Class<?> clazz, final String fieldname) {
    final String cap = StringUtils.capitalize(fieldname);
    final Method[] methods = clazz.getMethods();
    for (final Method method : methods) {
        if (("get" + cap).equals(method.getName()) == true || ("is" + cap).equals(method.getName()) == true) {
            if (method.isBridge() == false) {
                // Don't return bridged methods (methods defined in interface or super class with different return type).
                return method;
            }/*from   w ww . j  a v  a2s . co  m*/
        }
    }
    return null;
}

From source file:org.springframework.beans.BeanUtils.java

/**
 * Find a method with the given method name and minimal parameters (best case: none)
 * in the given list of methods.//from  www.  j  a  v  a2 s . co m
 * @param methods the methods to check
 * @param methodName the name of the method to find
 * @return the Method object, or {@code null} if not found
 * @throws IllegalArgumentException if methods of the given name were found but
 * could not be resolved to a unique method with minimal parameters
 */
@Nullable
public static Method findMethodWithMinimalParameters(Method[] methods, String methodName)
        throws IllegalArgumentException {

    Method targetMethod = null;
    int numMethodsFoundWithCurrentMinimumArgs = 0;
    for (Method method : methods) {
        if (method.getName().equals(methodName)) {
            int numParams = method.getParameterCount();
            if (targetMethod == null || numParams < targetMethod.getParameterCount()) {
                targetMethod = method;
                numMethodsFoundWithCurrentMinimumArgs = 1;
            } else if (!method.isBridge() && targetMethod.getParameterCount() == numParams) {
                if (targetMethod.isBridge()) {
                    // Prefer regular method over bridge...
                    targetMethod = method;
                } else {
                    // Additional candidate with same length
                    numMethodsFoundWithCurrentMinimumArgs++;
                }
            }
        }
    }
    if (numMethodsFoundWithCurrentMinimumArgs > 1) {
        throw new IllegalArgumentException("Cannot resolve method '" + methodName
                + "' to a unique method. Attempted to resolve to overloaded method with "
                + "the least number of parameters but there were " + numMethodsFoundWithCurrentMinimumArgs
                + " candidates.");
    }
    return targetMethod;
}

From source file:org.springframework.beans.GenericTypeAwarePropertyDescriptor.java

public GenericTypeAwarePropertyDescriptor(Class<?> beanClass, String propertyName, @Nullable Method readMethod,
        @Nullable Method writeMethod, Class<?> propertyEditorClass) throws IntrospectionException {

    super(propertyName, null, null);
    this.beanClass = beanClass;

    Method readMethodToUse = (readMethod != null ? BridgeMethodResolver.findBridgedMethod(readMethod) : null);
    Method writeMethodToUse = (writeMethod != null ? BridgeMethodResolver.findBridgedMethod(writeMethod)
            : null);//from  w ww.j ava 2s  .c  om
    if (writeMethodToUse == null && readMethodToUse != null) {
        // Fallback: Original JavaBeans introspection might not have found matching setter
        // method due to lack of bridge method resolution, in case of the getter using a
        // covariant return type whereas the setter is defined for the concrete property type.
        Method candidate = ClassUtils.getMethodIfAvailable(this.beanClass,
                "set" + StringUtils.capitalize(getName()), (Class<?>[]) null);
        if (candidate != null && candidate.getParameterCount() == 1) {
            writeMethodToUse = candidate;
        }
    }
    this.readMethod = readMethodToUse;
    this.writeMethod = writeMethodToUse;

    if (this.writeMethod != null) {
        if (this.readMethod == null) {
            // Write method not matched against read method: potentially ambiguous through
            // several overloaded variants, in which case an arbitrary winner has been chosen
            // by the JDK's JavaBeans Introspector...
            Set<Method> ambiguousCandidates = new HashSet<>();
            for (Method method : beanClass.getMethods()) {
                if (method.getName().equals(writeMethodToUse.getName()) && !method.equals(writeMethodToUse)
                        && !method.isBridge()
                        && method.getParameterCount() == writeMethodToUse.getParameterCount()) {
                    ambiguousCandidates.add(method);
                }
            }
            if (!ambiguousCandidates.isEmpty()) {
                this.ambiguousWriteMethods = ambiguousCandidates;
            }
        }
        this.writeMethodParameter = new MethodParameter(this.writeMethod, 0);
        GenericTypeResolver.resolveParameterType(this.writeMethodParameter, this.beanClass);
    }

    if (this.readMethod != null) {
        this.propertyType = GenericTypeResolver.resolveReturnType(this.readMethod, this.beanClass);
    } else if (this.writeMethodParameter != null) {
        this.propertyType = this.writeMethodParameter.getParameterType();
    }

    this.propertyEditorClass = propertyEditorClass;
}

From source file:org.springframework.integration.util.MessagingMethodInvokerHelper.java

private Map<Class<?>, HandlerMethod> findHandlerMethodsForTarget(final Object targetObject,
        final Class<? extends Annotation> annotationType, final String methodName,
        final boolean requiresReply) {

    final Map<Class<?>, HandlerMethod> candidateMethods = new HashMap<Class<?>, HandlerMethod>();
    final Map<Class<?>, HandlerMethod> fallbackMethods = new HashMap<Class<?>, HandlerMethod>();
    final AtomicReference<Class<?>> ambiguousFallbackType = new AtomicReference<Class<?>>();
    final Class<?> targetClass = this.getTargetClass(targetObject);
    MethodFilter methodFilter = new UniqueMethodFilter(targetClass);
    ReflectionUtils.doWithMethods(targetClass, new MethodCallback() {
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            boolean matchesAnnotation = false;
            if (method.isBridge()) {
                return;
            }//  w  ww  .  ja va2s.c  o  m
            if (isMethodDefinedOnObjectClass(method)) {
                return;
            }
            if (method.getDeclaringClass().equals(Proxy.class)) {
                return;
            }
            if (!Modifier.isPublic(method.getModifiers())) {
                return;
            }
            if (requiresReply && void.class.equals(method.getReturnType())) {
                return;
            }
            if (methodName != null && !methodName.equals(method.getName())) {
                return;
            }
            if (annotationType != null && AnnotationUtils.findAnnotation(method, annotationType) != null) {
                matchesAnnotation = true;
            }
            HandlerMethod handlerMethod = null;
            try {
                handlerMethod = new HandlerMethod(method, canProcessMessageList);
            } catch (Exception e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Method [" + method + "] is not eligible for Message handling.", e);
                }
                return;
            }
            Class<?> targetParameterType = handlerMethod.getTargetParameterType().getObjectType();
            if (matchesAnnotation || annotationType == null) {
                Assert.isTrue(!candidateMethods.containsKey(targetParameterType),
                        "Found more than one method match for type [" + targetParameterType + "]");
                candidateMethods.put(targetParameterType, handlerMethod);
            } else {
                if (fallbackMethods.containsKey(targetParameterType)) {
                    // we need to check for duplicate type matches,
                    // but only if we end up falling back
                    // and we'll only keep track of the first one
                    ambiguousFallbackType.compareAndSet(null, targetParameterType);
                }
                fallbackMethods.put(targetParameterType, handlerMethod);
            }
        }
    }, methodFilter);
    if (!candidateMethods.isEmpty()) {
        return candidateMethods;
    }
    if ((fallbackMethods.isEmpty() || ambiguousFallbackType.get() != null)
            && ServiceActivator.class.equals(annotationType)) {
        // a Service Activator can fallback to either MessageHandler.handleMessage(m) or RequestReplyExchanger.exchange(m)
        List<Method> frameworkMethods = new ArrayList<Method>();
        Class<?>[] allInterfaces = org.springframework.util.ClassUtils.getAllInterfacesForClass(targetClass);
        for (Class<?> iface : allInterfaces) {
            try {
                if ("org.springframework.integration.gateway.RequestReplyExchanger".equals(iface.getName())) {
                    frameworkMethods.add(targetClass.getMethod("exchange", Message.class));
                } else if ("org.springframework.integration.core.MessageHandler".equals(iface.getName())
                        && !requiresReply) {
                    frameworkMethods.add(targetClass.getMethod("handleMessage", Message.class));
                }
            } catch (Exception e) {
                // should never happen (but would fall through to errors below)
            }
        }
        if (frameworkMethods.size() == 1) {
            HandlerMethod handlerMethod = new HandlerMethod(frameworkMethods.get(0), canProcessMessageList);
            return Collections.<Class<?>, HandlerMethod>singletonMap(Object.class, handlerMethod);
        }
    }
    Assert.notEmpty(fallbackMethods, "Target object of type [" + this.targetObject.getClass()
            + "] has no eligible methods for handling Messages.");
    Assert.isNull(ambiguousFallbackType.get(), "Found ambiguous parameter type [" + ambiguousFallbackType
            + "] for method match: " + fallbackMethods.values());
    return fallbackMethods;
}

From source file:org.springframework.statemachine.processor.StateMachineMethodInvokerHelper.java

private Map<String, Map<Class<?>, HandlerMethod>> findHandlerMethodsForTarget(final Object targetObject,
        final Class<? extends Annotation> annotationType, final String methodName,
        final boolean requiresReply) {

    Map<String, Map<Class<?>, HandlerMethod>> handlerMethods = new HashMap<String, Map<Class<?>, HandlerMethod>>();

    final Map<Class<?>, HandlerMethod> candidateMethods = new HashMap<Class<?>, HandlerMethod>();
    final Map<Class<?>, HandlerMethod> candidateMessageMethods = new HashMap<Class<?>, HandlerMethod>();
    final Class<?> targetClass = this.getTargetClass(targetObject);
    MethodFilter methodFilter = new UniqueMethodFilter(targetClass);
    ReflectionUtils.doWithMethods(targetClass, new MethodCallback() {
        @Override/*from w  ww. j a  v a2s  .c o  m*/
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            boolean matchesAnnotation = false;
            if (method.isBridge()) {
                return;
            }
            if (isMethodDefinedOnObjectClass(method)) {
                return;
            }
            if (method.getDeclaringClass().equals(Proxy.class)) {
                return;
            }
            if (!Modifier.isPublic(method.getModifiers())) {
                return;
            }
            if (requiresReply && void.class.equals(method.getReturnType())) {
                return;
            }
            if (methodName != null && !methodName.equals(method.getName())) {
                return;
            }
            if (annotationType != null && AnnotationUtils.findAnnotation(method, annotationType) != null) {
                matchesAnnotation = true;
            }
            HandlerMethod handlerMethod = null;
            try {
                handlerMethod = new HandlerMethod(method);
            } catch (Exception e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Method [" + method + "] is not eligible for container handling.", e);
                }
                return;
            }
            Class<?> targetParameterType = handlerMethod.getTargetParameterType();
            if (matchesAnnotation || annotationType == null) {
                if (handlerMethod.isMessageMethod()) {
                    if (candidateMessageMethods.containsKey(targetParameterType)) {
                        throw new IllegalArgumentException("Found more than one method match for type "
                                + "[Message<" + targetParameterType + ">]");
                    }
                    candidateMessageMethods.put(targetParameterType, handlerMethod);
                } else {
                    if (candidateMethods.containsKey(targetParameterType)) {
                        String exceptionMessage = "Found more than one method match for ";
                        if (Void.class.equals(targetParameterType)) {
                            exceptionMessage += "empty parameter for 'payload'";
                        } else {
                            exceptionMessage += "type [" + targetParameterType + "]";
                        }
                        throw new IllegalArgumentException(exceptionMessage);
                    }
                    candidateMethods.put(targetParameterType, handlerMethod);
                }
            }
        }
    }, methodFilter);

    if (!candidateMethods.isEmpty() || !candidateMessageMethods.isEmpty()) {
        handlerMethods.put(CANDIDATE_METHODS, candidateMethods);
        handlerMethods.put(CANDIDATE_MESSAGE_METHODS, candidateMessageMethods);
        return handlerMethods;
    }

    Assert.state(!handlerMethods.isEmpty(), "Target object of type [" + this.targetObject.getClass()
            + "] has no eligible methods for handling Container.");

    return handlerMethods;
}