Example usage for java.lang.reflect Method getDeclaringClass

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

Introduction

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

Prototype

@Override
public Class<?> getDeclaringClass() 

Source Link

Document

Returns the Class object representing the class or interface that declares the method represented by this object.

Usage

From source file:Main.java

/**
 * find the setter method and set the value.
 *//* w w w . j a  v a2  s  .  co m*/
public static void setProperties(Object bean, Map<String, Object> properties) {
    for (Method method : bean.getClass().getMethods()) {
        String name = method.getName();
        if (name.length() > 3 && name.startsWith("set") && Modifier.isPublic(method.getModifiers())
                && method.getParameterTypes().length == 1 && method.getDeclaringClass() != Object.class) {
            String key = name.substring(3, 4).toLowerCase() + name.substring(4);
            try {
                Object value = properties.get(key);
                if (value != null) {
                    method.invoke(bean,
                            new Object[] { convertCompatibleType(value, method.getParameterTypes()[0]) });
                }
            } catch (Exception e) {
            }
        }
    }
}

From source file:com.sun.faces.el.impl.BeanInfoManager.java

/**
 * Returns a publicly-accessible version of the given method, by
 * searching for a public declaring class.
 *///from   w  w  w  .  j ava 2  s .  c  o m
static Method getPublicMethod(Method pMethod) {
    if (pMethod == null) {
        return null;
    }

    // See if the method is already available from a public class
    Class cl = pMethod.getDeclaringClass();
    if (Modifier.isPublic(cl.getModifiers())) {
        return pMethod;
    }

    // Otherwise, try to find a public class that declares the method
    Method ret = getPublicMethod(cl, pMethod);
    if (ret != null) {
        return ret;
    } else {
        return pMethod;
    }
}

From source file:com.github.hateoas.forms.spring.AffordanceBuilder.java

/**
 * @param method must not be {@literal null}.
 * @param parameters additional parameters.
 * @return builder/*ww w  .  j a  v a  2 s .  c  o m*/
 * 
 * @see org.springframework.hateoas.MethodLinkBuilderFactory#linkTo(Method, Object...)
 */
public static AffordanceBuilder linkTo(final Method method, final Object... parameters) {
    return FACTORY.linkTo(method.getDeclaringClass(), method, parameters);
}

From source file:com.github.valdr.thirdparty.spring.AnnotationUtils.java

/**
 * Get a single {@link java.lang.annotation.Annotation} of {@code annotationType} from the supplied {@link java.lang.reflect.Method},
 * traversing its super methods if no annotation can be found on the given method itself.
 * <p>Annotations on methods are not inherited by default, so we need to handle this explicitly.
 * @param method the method to look for annotations on
 * @param annotationType the annotation class to look for
 * @return the annotation found, or {@code null} if none found
 *///from w  w w.j  av  a2  s  .com
public static <A extends Annotation> A findAnnotation(Method method, Class<A> annotationType) {
    A annotation = getAnnotation(method, annotationType);
    Class<?> clazz = method.getDeclaringClass();
    if (annotation == null) {
        annotation = searchOnInterfaces(method, annotationType, clazz.getInterfaces());
    }
    while (annotation == null) {
        clazz = clazz.getSuperclass();
        if (clazz == null || clazz.equals(Object.class)) {
            break;
        }
        try {
            Method equivalentMethod = clazz.getDeclaredMethod(method.getName(), method.getParameterTypes());
            annotation = getAnnotation(equivalentMethod, annotationType);
        } catch (NoSuchMethodException ex) {
            // No equivalent method found
        }
        if (annotation == null) {
            annotation = searchOnInterfaces(method, annotationType, clazz.getInterfaces());
        }
    }
    return annotation;
}

From source file:org.apache.brooklyn.util.javalang.MethodAccessibleReflections.java

/**
 * @see {@link Reflections#findAccessibleMethod(Method)}
 *///from   w  w  w.j av a2s. com
// Similar to org.apache.commons.lang3.reflect.MethodUtils.getAccessibleMethod
// We could delegate to that, but currently brooklyn-utils-common doesn't depend on commons-lang3; maybe it should?
static Maybe<Method> findAccessibleMethod(Method method) {
    if (!isAccessible(method)) {
        String err = "Method is not public, so not normally accessible for " + method;
        if (FIND_ACCESSIBLE_FAILED_LOGGED_METHODS.add(method.toString())) {
            LOG.warn(err + "; usage may subsequently fail");
        }
        return Maybe.absent(err);
    }

    boolean declaringClassAccessible = isAccessible(method.getDeclaringClass());
    if (declaringClassAccessible) {
        return Maybe.of(method);
    }

    // reflectively calling a public method on a private class can fail (unless one first 
    // calls setAccessible). Check if this overrides a public method on a public super-type
    // that we can call instead!

    if (Modifier.isStatic(method.getModifiers())) {
        String err = "Static method not declared on a public class, so not normally accessible for " + method;
        if (FIND_ACCESSIBLE_FAILED_LOGGED_METHODS.add(method.toString())) {
            LOG.warn(err + "; usage may subsequently fail");
        }
        return Maybe.absent(err);
    }

    Maybe<Method> altMethod = tryFindAccessibleEquivalent(method);

    if (altMethod.isPresent()) {
        LOG.debug("Switched method for publicly accessible equivalent: method={}; origMethod={}",
                altMethod.get(), method);
        return altMethod;
    } else {
        String err = "No accessible (overridden) method found in public super-types for method " + method;
        if (FIND_ACCESSIBLE_FAILED_LOGGED_METHODS.add(method.toString())) {
            LOG.warn(err);
        }
        return Maybe.absent(err);
    }
}

From source file:ReflectUtil.java

/**
 * <p>Attempts to find an accessible version of the method passed in, where accessible
 * is defined as the method itself being public and the declaring class being public.
 * Mostly useful as a workaround to the situation when
 * {@link PropertyDescriptor#getReadMethod()} and/or
 * {@link java.beans.PropertyDescriptor#getWriteMethod()} returns methods that are not
 * accessible (usually due to public implementations of interface methods in private
 * classes).</p>/*  w  w w  .j  ava 2 s  . com*/
 *
 * <p>Checks the method passed in and if it already meets these criteria it is returned
 * immediately. In general this leads to very little performance overhead</p>
 *
 * <p>If the method does not meet the criteria then the class' interfaces are scanned
 * for a matching method. If one is not found, then the class' superclass hierarchy
 * is searched. Finally, if no matching method can be found the original method is
 * returned.</p>
 *
 * @param m a method that may or may not be accessible
 * @return either an accessible version of the same method, or the method passed in if
 *         an accessible version cannot be found
 */
public static Method findAccessibleMethod(final Method m) {
    // If the passed in method is accessible, then just give it back.
    if (isPublic(m.getModifiers()) && isPublic(m.getDeclaringClass().getModifiers()))
        return m;
    if (m.isAccessible())
        return m;

    final Class<?> clazz = m.getDeclaringClass();
    final String name = m.getName();
    final Class<?>[] ptypes = m.getParameterTypes();

    // Else, loop through the interfaces for the declaring class, looking for a
    // public version of the method that we can call
    for (Class<?> iface : clazz.getInterfaces()) {
        try {
            Method m2 = iface.getMethod(name, ptypes);
            if (m2.isAccessible())
                return m2;
            if (isPublic(iface.getModifiers()) && isPublic(m2.getModifiers()))
                return m2;
        } catch (NoSuchMethodException nsme) {
            /* Not Unexpected. */ }
    }

    // Else loop through the superclasses looking for a public method
    Class<?> c = clazz.getSuperclass();
    while (c != null) {
        try {
            Method m2 = c.getMethod(name, ptypes);
            if (m2.isAccessible())
                return m2;
            if (isPublic(c.getModifiers()) && isPublic(m2.getModifiers()))
                return m2;
        } catch (NoSuchMethodException nsme) {
            /* Not Unexpected. */ }

        c = c.getSuperclass();
    }

    // If we haven't found anything at this point, just give up!
    return m;
}

From source file:jenkins.plugins.git.MethodUtils.java

/**
 * <p>Retrieves a method whether or not it's accessible. If no such method
 * can be found, return {@code null}.</p>
 *
 * @param cls            The class that will be subjected to the method search
 * @param methodName     The method that we wish to call
 * @param parameterTypes Argument class types
 * @return The method//from ww  w  .ja  v a 2  s. c o  m
 */
static Method getMethodImpl(final Class<?> cls, final String methodName, final Class<?>... parameterTypes) {
    Validate.notNull(cls, "Null class not allowed.");
    Validate.notEmpty(methodName, "Null or blank methodName not allowed.");

    // fast path, check if directly declared on the class itself
    for (final Method method : cls.getDeclaredMethods()) {
        if (methodName.equals(method.getName()) && Arrays.equals(parameterTypes, method.getParameterTypes())) {
            return method;
        }
    }
    if (!cls.isInterface()) {
        // ok, now check if directly implemented on a superclass
        // Java 8: note that super-interface implementations trump default methods
        for (Class<?> klass = cls.getSuperclass(); klass != null; klass = klass.getSuperclass()) {
            for (final Method method : klass.getDeclaredMethods()) {
                if (methodName.equals(method.getName())
                        && Arrays.equals(parameterTypes, method.getParameterTypes())) {
                    return method;
                }
            }
        }
    }
    // ok, now we are looking for an interface method... the most specific one
    // in the event that we have two unrelated interfaces both declaring a method of the same name
    // we will give up and say we could not find the method (the logic here is that we are primarily
    // checking for overrides, in the event of a Java 8 default method, that default only
    // applies if there is no conflict from an unrelated interface... thus if there are
    // default methods and they are unrelated then they don't exist... if there are multiple unrelated
    // abstract methods... well they won't count as a non-abstract implementation
    Method res = null;
    for (final Class<?> klass : (List<Class<?>>) ClassUtils.getAllInterfaces(cls)) {
        for (final Method method : klass.getDeclaredMethods()) {
            if (methodName.equals(method.getName())
                    && Arrays.equals(parameterTypes, method.getParameterTypes())) {
                if (res == null) {
                    res = method;
                } else {
                    Class<?> c = res.getDeclaringClass();
                    if (c == klass) {
                        // match, ignore
                    } else if (c.isAssignableFrom(klass)) {
                        // this is a more specific match
                        res = method;
                    } else if (!klass.isAssignableFrom(c)) {
                        // multiple overlapping interfaces declare this method and there is no common ancestor
                        return null;

                    }
                }
            }
        }
    }
    return res;
}

From source file:com.mawujun.utils.AnnotationUtils.java

/**
 * Get a single {@link Annotation} of {@code annotationType} from the supplied {@link Method},
 * traversing its super methods if no annotation can be found on the given method itself.
 * <p>Annotations on methods are not inherited by default, so we need to handle this explicitly.
 * @param method the method to look for annotations on
 * @param annotationType the annotation class to look for
 * @return the annotation found, or {@code null} if none found
 *//*from w  w  w  . jav a2 s. c o  m*/
public static <A extends Annotation> A findAnnotation(Method method, Class<A> annotationType) {
    A annotation = getAnnotation(method, annotationType);
    Class<?> cl = method.getDeclaringClass();
    if (annotation == null) {
        annotation = searchOnInterfaces(method, annotationType, cl.getInterfaces());
    }
    while (annotation == null) {
        cl = cl.getSuperclass();
        if (cl == null || cl == Object.class) {
            break;
        }
        try {
            Method equivalentMethod = cl.getDeclaredMethod(method.getName(), method.getParameterTypes());
            annotation = getAnnotation(equivalentMethod, annotationType);
        } catch (NoSuchMethodException ex) {
            // No equivalent method found
        }
        if (annotation == null) {
            annotation = searchOnInterfaces(method, annotationType, cl.getInterfaces());
        }
    }
    return annotation;
}

From source file:com.offbynull.coroutines.instrumenter.asm.SearchUtils.java

/**
 * Find invocations of a certain method.
 * @param insnList instruction list to search through
 * @param expectedMethod type of method being invoked
 * @return list of invocations (may be nodes of type {@link MethodInsnNode} or {@link InvokeDynamicInsnNode})
 * @throws NullPointerException if any argument is {@code null}
 * @throws NullPointerException if {@code expectedMethodType} isn't of sort {@link Type#METHOD}
 *//* ww  w .j  a  va 2 s  . c om*/
public static List<AbstractInsnNode> findInvocationsOf(InsnList insnList, Method expectedMethod) {
    Validate.notNull(insnList);
    Validate.notNull(expectedMethod);

    List<AbstractInsnNode> ret = new ArrayList<>();

    Type expectedMethodDesc = Type.getType(expectedMethod);
    Type expectedMethodOwner = Type.getType(expectedMethod.getDeclaringClass());
    String expectedMethodName = expectedMethod.getName();

    Iterator<AbstractInsnNode> it = insnList.iterator();
    while (it.hasNext()) {
        AbstractInsnNode instructionNode = it.next();

        Type methodDesc;
        Type methodOwner;
        String methodName;
        if (instructionNode instanceof MethodInsnNode) {
            MethodInsnNode methodInsnNode = (MethodInsnNode) instructionNode;
            methodDesc = Type.getType(methodInsnNode.desc);
            methodOwner = Type.getObjectType(methodInsnNode.owner);
            methodName = expectedMethod.getName();
        } else {
            continue;
        }

        if (methodDesc.equals(expectedMethodDesc) && methodOwner.equals(expectedMethodOwner)
                && methodName.equals(expectedMethodName)) {
            ret.add(instructionNode);
        }
    }

    return ret;
}

From source file:org.apache.sling.scripting.sightly.impl.engine.runtime.RenderContextImpl.java

private static Method extractMethodInheritanceChain(Class type, Method m) {
    if (m == null || Modifier.isPublic(type.getModifiers())) {
        return m;
    }/*from  w w w.  j a v  a 2s.c om*/
    Class[] inf = type.getInterfaces();
    Method mp;
    for (Class<?> iface : inf) {
        try {
            mp = iface.getMethod(m.getName(), m.getParameterTypes());
            mp = extractMethodInheritanceChain(mp.getDeclaringClass(), mp);
            if (mp != null) {
                return mp;
            }
        } catch (NoSuchMethodException e) {
            // do nothing
        }
    }
    Class<?> sup = type.getSuperclass();
    if (sup != null) {
        try {
            mp = sup.getMethod(m.getName(), m.getParameterTypes());
            mp = extractMethodInheritanceChain(mp.getDeclaringClass(), mp);
            if (mp != null) {
                return mp;
            }
        } catch (NoSuchMethodException e) {
            // do nothing
        }
    }
    return null;
}