Example usage for java.lang.reflect Method equals

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

Introduction

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

Prototype

public boolean equals(Object obj) 

Source Link

Document

Compares this Method against the specified object.

Usage

From source file:org.alfresco.rest.framework.jacksonextensions.CustomAnnotationIntrospector.java

@Override
public String findGettablePropertyName(AnnotatedMethod am) {
    Method uniqueIdMethod = ResourceInspector.findUniqueIdMethod(am.getDeclaringClass());
    if (uniqueIdMethod != null && uniqueIdMethod.equals(am.getMember())) {
        {//from  ww  w .ja v  a  2 s  .  c  o  m
            String uniqueIdPropertyName = ResourceInspector.findUniqueIdName(uniqueIdMethod);
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "Changing the name of property: " + am.getFullName() + " to " + uniqueIdPropertyName);
            }

            return uniqueIdPropertyName;
        }
    }
    return super.findGettablePropertyName(am);
}

From source file:org.apache.cocoon.components.source.impl.BlockContextSource.java

private static Source adjustName(final TraversableSource source, final String blockName) {
    TraversableSource adjustedSource = (TraversableSource) Proxy.newProxyInstance(
            source.getClass().getClassLoader(), ClassUtils.getAllInterfaces(source), new InvocationHandler() {

                /* (non-Javadoc)
                 * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
                 *///from   ww  w. j a  va 2s  .  c  o  m
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if (method.equals(TraversableSource.class.getMethod("getName", new Class[] {})))
                        return blockName;
                    else
                        return method.invoke(source, args);
                }
            });
    return adjustedSource;
}

From source file:org.apache.dubbo.config.spring.beans.factory.annotation.CompatibleReferenceAnnotationBeanPostProcessor.java

/**
 * Finds {@link InjectionMetadata.InjectedElement} Metadata from annotated {@link Reference @Reference} methods
 *
 * @param beanClass The {@link Class} of Bean
 * @return non-null {@link List}//from  w  w w .j  a v  a 2 s  . c  o  m
 */
private List<ReferenceMethodElement> findMethodReferenceMetadata(final Class<?> beanClass) {

    final List<ReferenceMethodElement> elements = new LinkedList<ReferenceMethodElement>();

    ReflectionUtils.doWithMethods(beanClass, new ReflectionUtils.MethodCallback() {
        @Override
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {

            Method bridgedMethod = findBridgedMethod(method);

            if (!isVisibilityBridgeMethodPair(method, bridgedMethod)) {
                return;
            }

            Reference reference = findAnnotation(bridgedMethod, Reference.class);

            if (reference != null && method.equals(ClassUtils.getMostSpecificMethod(method, beanClass))) {
                if (Modifier.isStatic(method.getModifiers())) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("@Reference annotation is not supported on static methods: " + method);
                    }
                    return;
                }
                if (method.getParameterTypes().length == 0) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("@Reference  annotation should only be used on methods with parameters: "
                                + method);
                    }
                }
                PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, beanClass);
                elements.add(new ReferenceMethodElement(method, pd, reference));
            }
        }
    });

    return elements;

}

From source file:org.apereo.portal.utils.cache.PersonDirectoryCacheKeyGenerator.java

/**
 * Iterates over the {@link CachableMethod} instances to determine which instance the
 * passed {@link MethodInvocation} applies to.
 *///from  w ww  . j a  v  a  2 s.  c  o  m
protected CachableMethod resolveCacheableMethod(Method targetMethod) {
    final Class<?> targetClass = targetMethod.getDeclaringClass();
    for (final CachableMethod cachableMethod : CachableMethod.values()) {
        Method cacheableMethod = null;
        try {
            cacheableMethod = targetClass.getMethod(cachableMethod.getName(), cachableMethod.getArgs());
        } catch (SecurityException e) {
            this.logger.warn("Security exception while attempting to if the target class '" + targetClass
                    + "' implements the cachable method '" + cachableMethod + "'", e);
        } catch (NoSuchMethodException e) {
            final String message = "Taret class '" + targetClass
                    + "' does not implement possible cachable method '" + cachableMethod
                    + "'. Is the advice applied to the correct bean and methods?";

            if (this.logger.isDebugEnabled()) {
                this.logger.debug(message, e);
            } else {
                this.logger.warn(message);
            }
        }

        if (targetMethod.equals(cacheableMethod)) {
            return cachableMethod;
        }
    }

    throw new IllegalArgumentException("Do not know how to generate a cache for for '" + targetMethod
            + "' on class '" + targetClass + "'. Is the advice applied to the correct bean and methods?");
}

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());
    }//from w  ww  .  jav a 2 s  .c  o m
    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.jgentleframework.core.factory.support.CoreProcessorImpl.java

@SuppressWarnings("unchecked")
@Override/*from  www . ja v a 2s.  c o  m*/
public Object handle(Selector targetSelector, Object previousResult)
        throws InvocationTargetException, IllegalArgumentException, SecurityException, InstantiationException,
        IllegalAccessException, NoSuchMethodException {

    if (!ReflectUtils.isCast(CoreInstantiationSelector.class, targetSelector)) {
        if (log.isFatalEnabled()) {
            log.fatal("Target selector can not be casted to '" + CoreInstantiationSelector.class.toString()
                    + "'");
        }
        throw new IllegalPropertyException(
                "Target selector can not be casted to '" + CoreInstantiationSelector.class.toString() + "'");
    }
    Object result = null;
    Definition definition = targetSelector.getDefinition();
    Class<?> targetClass = targetSelector.getTargetClass();
    CoreInstantiationSelector selector = (CoreInstantiationSelector) targetSelector;
    boolean runtimeLoading = definition != null && definition.isAnnotationPresent(AlwaysReload.class)
            ? definition.getAnnotation(AlwaysReload.class).value()
            : false;
    // create bean instance
    if (targetSelector instanceof InstantiationSelectorImpl) {
        InstantiationSelector instSelector = (InstantiationSelector) targetSelector;
        // nu bean  c khi to 1 phn trc 
        if (previousResult != null && (targetClass.isAnnotation() || targetClass.isInterface())) {
            throw new InterceptionException(
                    "Bean instantiation is not supported or completed if target class is "
                            + "annotation or interface and if at least one 'instantiation' interceptor "
                            + "has instantiated the corresponding 'object bean'");
        } else {
            Map<Method, MethodAspectPair> methodAspectList = new HashMap<Method, MethodAspectPair>();
            Map<Interceptor, Matcher<Definition>> map = instSelector.getMapMatcherInterceptor();
            final List<Method> methodList = new ArrayList<Method>();
            final Field[] fieldList = ReflectUtils.getDeclaredFields(targetClass, false, true);
            Enhancer.getMethods(targetClass, null, methodList);
            boolean invocationINOUT = false;
            ElementAspectFactory elementAspectFactory = new ElementAspectFactory();
            /*
             * perform method interceptor
             */
            MethodInterceptor[] methodIcptLst = instSelector.getMethodInterceptors();
            for (Method method : methodList) {
                invocationINOUT = invocationINOUT == false ? InterceptorUtils.isInvocation(definition, method)
                        : invocationINOUT;
                // creates Aspect Pair
                MethodAspectPair aspectPair = elementAspectFactory.analysesMethod(methodIcptLst, map,
                        definition, method);
                // performs advice
                executesAdvice(definition, method, provider, runtimeLoading, aspectPair);
                if (aspectPair.hasInterceptors())
                    methodAspectList.put(method, aspectPair);
            }
            /*
             * perform field interceptor
             */
            FieldInterceptor[] fieldIcpLst = instSelector.getFieldInterceptors();
            if (!targetClass.isAnnotation()) {
                for (Field field : fieldList) {
                    invocationINOUT = invocationINOUT == false
                            ? InterceptorUtils.isInvocation(definition, field)
                            : invocationINOUT;
                    // creates Aspect Pair
                    FieldAspectPair fieldAspectPair = elementAspectFactory.analysesField(fieldIcpLst, map,
                            definition, field);
                    if (fieldAspectPair.hasInterceptors()) {
                        Method setter = Utils.getDefaultSetter(targetClass, field.getName());
                        Method getter = Utils.getDefaultGetter(targetClass, field.getName());
                        if (getter == null || setter == null) {
                            throw new InterceptionException(
                                    "Does not found setter or getter of field '" + field.getName() + "'");
                        }
                        MethodInterceptor interceptor = InterceptorUtils
                                .createsFieldStackMethodInterceptor(field);
                        if (methodAspectList.containsKey(setter))
                            methodAspectList.get(setter).add(interceptor);
                        else
                            methodAspectList.put(setter, new MethodAspectPair(setter, interceptor));
                        if (methodAspectList.containsKey(getter))
                            methodAspectList.get(getter).add(interceptor);
                        else
                            methodAspectList.put(getter, new MethodAspectPair(getter, interceptor));
                    }
                }
            }
            /*
             * perform invocation in/out or annotation attributes injection
             */
            executesInOut(targetClass, definition, provider, runtimeLoading, methodAspectList, invocationINOUT);
            // Creates callbacks.
            Callback[] callbacks = new Callback[methodList.size() + 1];
            Class<? extends Callback>[] callbackTypes = new Class[methodList.size() + 1];
            for (int i = 0; i < methodList.size(); i++) {
                MethodAspectPair pair = methodAspectList.get(methodList.get(i));
                if (pair == null) {
                    callbacks[i] = NoOp.INSTANCE;
                    callbackTypes[i] = NoOp.class;
                } else {
                    callbacks[i] = new MethodInterceptorStackCallback(pair.getMethod(), previousResult,
                            pair.interceptors.toArray(new MethodInterceptor[pair.interceptors.size()]));
                    callbackTypes[i] = net.sf.cglib.proxy.MethodInterceptor.class;
                }
            }
            callbacks[methodList.size()] = new ReturnScopeNameMethodInterceptor(selector.getScopeName());
            callbackTypes[methodList.size()] = net.sf.cglib.proxy.MethodInterceptor.class;
            // Nu khng tm thy bt k ch nh khi to interceptor no
            // ==> t ng return null.
            if (methodAspectList.size() == 0 && (targetClass.isInterface())) {
                return NullClass.class;
            }
            // Create the proxied class.
            final Method returnScopeNameMethod = ReturnScopeName.class.getDeclaredMethod("returnsScopeName");
            Enhancer enhancer = new Enhancer();
            if (targetClass.isAnnotation() || targetClass.isInterface())
                enhancer.setInterfaces(new Class<?>[] { targetClass, ReturnScopeName.class });
            else {
                enhancer.setSuperclass(targetClass);
                enhancer.setInterfaces(new Class<?>[] { ReturnScopeName.class });
            }
            enhancer.setCallbackFilter(new CallbackFilter() {
                public int accept(Method method) {

                    if (method.equals(returnScopeNameMethod))
                        return methodList.size();
                    return methodList.indexOf(method);
                }
            });
            enhancer.setCallbackTypes(callbackTypes);
            enhancer.setUseFactory(false);
            enhancer.setUseCache(true);
            enhancer.setNamingPolicy(new JGentleNamingPolicy());
            Class<?> proxied = enhancer.createClass();
            Enhancer.registerStaticCallbacks(proxied, callbacks);
            MetaDefObject metaObj = new MetaDefObject();
            findInOutNonRuntime(metaObj, definition);
            CachedConstructor cons = Utils.createConstructionProxy(definition, proxied,
                    instSelector.getArgTypes(), metaObj);
            selector.getCachingList().put(definition, cons);
            result = cons.newInstance(instSelector.getArgs());
            // executes process after bean is created
            prepareSingletonBean(selector, provider, result);
            CommonFactory.singleton().executeProcessAfterBeanCreated(targetClass, metaObj, provider, result,
                    definition);
        }
    } else if (targetSelector instanceof CoreInstantiationSelectorImpl
            && !(targetSelector instanceof InstantiationSelectorImpl)) {
        result = createPureBeanInstance(targetSelector, targetClass, definition, provider, runtimeLoading);
    }
    return result;
}

From source file:org.jgentleframework.core.factory.support.CoreProcessorImpl.java

@SuppressWarnings("unchecked")
@Override/* w w  w.ja v a2s .c  o  m*/
protected CachedConstructor createConstructionProxy(CoreInstantiationSelector selector, MetaDefObject mdo)
        throws SecurityException, NoSuchMethodException {

    Assertor.notNull(selector,
            "The selector [" + CoreInstantiationSelector.class.toString() + "] must not be null !");
    // Create
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(selector.getTargetClass());
    enhancer.setInterfaces(new Class<?>[] { ReturnScopeName.class });
    Callback[] callbacks = new Callback[] { NoOp.INSTANCE,
            new ReturnScopeNameMethodInterceptor(selector.getScopeName()) };
    final Method returnScopeNameMethod = ReturnScopeName.class.getDeclaredMethod("returnsScopeName");
    Class<? extends Callback>[] callbackTypes = new Class[] { NoOp.class,
            net.sf.cglib.proxy.MethodInterceptor.class };
    enhancer.setCallbackFilter(new CallbackFilter() {
        @Override
        public int accept(Method method) {

            if (method.equals(returnScopeNameMethod))
                return 1;
            return 0;
        }
    });
    enhancer.setCallbackTypes(callbackTypes);
    enhancer.setUseFactory(false);
    enhancer.setUseCache(true);
    enhancer.setNamingPolicy(new JGentleNamingPolicy());
    Class<?> proxied = enhancer.createClass();
    // Store callbacks.
    Enhancer.registerStaticCallbacks(proxied, callbacks);
    CachedConstructor cons = Utils.createConstructionProxy(selector.getDefinition(), proxied,
            selector.getArgTypes(), mdo);
    return cons;
}

From source file:org.jgentleframework.core.factory.support.CoreProcessorImpl.java

@SuppressWarnings("unchecked")
@Override//from   w  w w  .j a  va 2s . co m
protected CachedConstructor createConstructionProxy(final CoreInstantiationSelector selector,
        Class<?> interfaze, net.sf.cglib.proxy.MethodInterceptor interceptor, final List<Method> methodList,
        MetaDefObject mdo) throws SecurityException, NoSuchMethodException {

    Assertor.notNull(interceptor, "The given interceptor must not be null !");
    Assertor.notNull(interceptor, "The given method list must not be null !");
    // Create
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(selector.getTargetClass());
    if (interfaze != null && interfaze.isAnnotation())
        enhancer.setInterfaces(new Class<?>[] { interfaze, Annotation.class, ReturnScopeName.class });
    else if (interfaze != null && interfaze.isInterface())
        enhancer.setInterfaces(new Class<?>[] { interfaze, ReturnScopeName.class });
    else {
        enhancer.setInterfaces(new Class<?>[] { ReturnScopeName.class });
    }
    final Method returnScopeNameMethod = ReturnScopeName.class.getDeclaredMethod("returnsScopeName");
    Callback[] callbacks = new Callback[] { NoOp.INSTANCE, interceptor,
            new ReturnScopeNameMethodInterceptor(selector.getScopeName()) };
    Class<? extends Callback>[] callbackTypes = new Class[] { NoOp.class,
            net.sf.cglib.proxy.MethodInterceptor.class, net.sf.cglib.proxy.MethodInterceptor.class };
    enhancer.setCallbackFilter(new CallbackFilter() {
        @Override
        public int accept(Method method) {

            if (methodList != null && methodList.contains(method) && !selector.getTargetClass().isAnnotation())
                return 1;
            else if (selector.getTargetClass().isAnnotation())
                return 1;
            else if (method.equals(returnScopeNameMethod))
                return 2;
            else
                return 0;
        }
    });
    enhancer.setCallbackTypes(callbackTypes);
    enhancer.setUseFactory(false);
    enhancer.setUseCache(true);
    enhancer.setNamingPolicy(new JGentleNamingPolicy());
    Class<?> proxied = enhancer.createClass();
    // Store callbacks.
    Enhancer.registerStaticCallbacks(proxied, callbacks);
    CachedConstructor cons = Utils.createConstructionProxy(selector.getDefinition(), proxied,
            selector.getArgTypes(), mdo);
    return cons;
}

From source file:org.jgentleframework.core.intercept.support.StaticMatcher.java

/**
 * Static method field matching.//from   ww  w .  java2s.  c o m
 * 
 * @param identification
 *            the identification
 * @param clazz
 *            the clazz
 * @param matching
 *            the matching
 * @return true, if successful
 */
@SuppressWarnings("unchecked")
public static boolean staticMethodFieldMatching(Identification<?> identification, Class<?> clazz,
        Matching matching) {

    boolean result = false;
    if (!ReflectUtils.isCast(clazz, identification)) {
        throw new MatchingException("The identification can not be cast to [" + clazz + "]");
    }
    Definition def = (Definition) matching.getMetadata(MetadataKey.DEFINITION).getValue();
    /*
     * X l kim tra identification trn method identification
     */
    if (MethodIdentification.class == clazz) {
        MethodIdentification mi = (MethodIdentification) identification;
        if (mi.getDeclaringClass() == null)
            mi.setDeclaringClass(def.getOwnerClass());
        for (Method method : mi.getMember()) {
            if (ReflectUtils.isCast(MethodConstructorMatching.class, matching)) {
                if (method.equals(((MethodConstructorMatching) matching).getElement())) {
                    result = true;
                    break;
                }
            } else if (ReflectUtils.isCast(ClassMatching.class, matching)) {
                if (method.equals(matching.getMetadata(MetadataKey.METHOD).getValue())) {
                    result = true;
                    break;
                }
            } else {
                if (log.isErrorEnabled())
                    log.error("The 'matching' can not be cast to [" + MethodConstructorMatching.class + "]",
                            new MatchingException());
            }
        }
    }
    /*
     * X l kim tra identification trn field identification
     */
    else if (FieldIdentification.class == clazz) {
        FieldIdentification mi = (FieldIdentification) identification;
        if (mi.getDeclaringClass() == null)
            mi.setDeclaringClass(def.getOwnerClass());
        for (Field field : mi.getMember()) {
            if (ReflectUtils.isCast(FieldMatching.class, matching)) {
                if (field.equals(((FieldMatching) matching).getField())) {
                    result = true;
                    break;
                }
            } else if (ReflectUtils.isCast(ClassMatching.class, matching)) {
                if (field.equals(matching.getMetadata(MetadataKey.FIELD).getValue())) {
                    result = true;
                    break;
                }
            } else {
                if (log.isErrorEnabled())
                    log.error("The 'matching' can not be cast to [" + FieldMatching.class + "]",
                            new MatchingException());
            }
        }
    }
    return result;
}

From source file:org.nuclos.client.layout.wysiwyg.component.properties.ComponentProperties.java

/**
 * /*from   w w  w.  j a  v a 2  s .  co m*/
 * @param newProperties
 * @throws CommonBusinessException
 */
public void setProperties(Map<String, PropertyValue<?>> newProperties) throws CommonBusinessException {
    try {
        if (c instanceof WYSIWYGLayoutEditorPanel)
            ((WYSIWYGLayoutEditorPanel) c).getUndoRedoFunction().loggingChangeComponentsProperties(c,
                    getClonedInstance(), ((WYSIWYGLayoutEditorPanel) c).getTableLayoutUtil());
        else
            c.getParentEditor().getUndoRedoFunction().loggingChangeComponentsProperties(c, getClonedInstance(),
                    c.getParentEditor().getTableLayoutUtil());
    } catch (CommonFatalException ex) {
    } catch (NullPointerException ex) {
    }

    for (Map.Entry<String, PropertyValue<?>> e : newProperties.entrySet()) {
        properties.put(e.getKey(), e.getValue());

        if (PropertyUtils.getValueClass(c, e.getKey()) != null) {
            Class<?> valueClass = PropertyUtils.getValueClass(c, e.getKey());
            if (c instanceof LayoutComponent) {
                LayoutComponent lc = (LayoutComponent) c;
                if (lc.getComponentProperties() != null) {
                    for (Property pt : lc.getComponentProperties()) {
                        if (pt.name.equals(e.getKey())) {
                            lc.setProperty(e.getKey(), e.getValue().getValue(valueClass, c));
                        }
                    }
                }
            }

            Class<? extends WYSIWYGComponent> componentClass = c.getClass();
            Collection<String> methodNames = getMethodForProperty(e.getKey());

            for (Iterator<String> it = methodNames.iterator(); it.hasNext();) {
                String methodName = it.next();
                try {
                    Method method = componentClass.getMethod(methodName, valueClass);
                    method.invoke(c, e.getValue().getValue(valueClass, c));
                    try {
                        if (method.equals(componentClass.getMethod("setPreferredSize", valueClass))) {
                            c.getParentEditor().getTableLayoutUtil().revalidateLayoutCellForComponent(c,
                                    ((Dimension) e.getValue().getValue(valueClass, c)));
                        }
                    } catch (Exception exc) {
                    }
                } catch (SecurityException ex) {
                    log.error(e);
                    Errors.getInstance().showExceptionDialog(null, ex);
                } catch (NoSuchMethodException ex) {
                    log.error(e);
                    Errors.getInstance().showExceptionDialog(null, ex);
                } catch (IllegalArgumentException ex) {
                    log.error(e);
                    Errors.getInstance().showExceptionDialog(null, ex);
                } catch (IllegalAccessException ex) {
                    log.error(e);
                    Errors.getInstance().showExceptionDialog(null, ex);
                } catch (InvocationTargetException ex) {
                    log.error(e);
                    Errors.getInstance().showExceptionDialog(null, ex);
                    if (ex.getTargetException() instanceof CommonBusinessException) {
                        throw (CommonBusinessException) ex.getTargetException();
                    } else {
                        throw new CommonFatalException(ex);
                    }
                }
            }
        }
    }

    for (Map.Entry<String, PropertyValue<?>> e : newProperties.entrySet()) {
        addStaticDependantProperties(e.getKey(), e.getValue());
    }

    try {
        if (c instanceof WYSIWYGLayoutEditorPanel)
            ((WYSIWYGLayoutEditorPanel) c).getUndoRedoFunction().loggingChangeComponentsProperties(c,
                    getClonedInstance(), ((WYSIWYGLayoutEditorPanel) c).getTableLayoutUtil());
        else
            c.getParentEditor().getUndoRedoFunction().loggingChangeComponentsProperties(c, getClonedInstance(),
                    c.getParentEditor().getTableLayoutUtil());
    } catch (CommonFatalException ex) {
    } catch (NullPointerException ex) {
    }
}