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:com.medsphere.fileman.FMRecord.java

/**
 * if the annotation is a method, get the setter for the method and invoke it.
 * @param ele//from   ww  w  .ja  va  2s  . co  m
 * @param method
 * @param obj
 */
private void invokeSetter(AnnotatedElement ele, Method method, Object obj) {
    String getter = method.getName();
    String setterName = getter.replaceFirst("get", "set");
    try {
        Method setter = method.getDeclaringClass().getMethod(setterName, obj.getClass());
        setter.invoke(this, obj);
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
        logger.error("Unable to find setter for " + ele.toString()
                + ".  Ensure that a setter exists for this field.  Expecting " + setterName);
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.haulmont.chile.core.loader.ChileAnnotationsLoader.java

protected boolean setterExists(Method getter) {
    if (getter.getName().startsWith("get")) {
        String setterName = "set" + getter.getName().substring(3);
        Method[] methods = getter.getDeclaringClass().getDeclaredMethods();
        for (Method method : methods) {
            if (setterName.equals(method.getName())) {
                return true;
            }/*ww  w. ja  va 2s  . c  o  m*/
        }
    }
    return false;
}

From source file:ca.uhn.fhir.rest.client.ClientInvocationHandler.java

@Override
public Object invoke(Object theProxy, Method theMethod, Object[] theArgs) throws Throwable {
    Object directRetVal = myMethodToReturnValue.get(theMethod);
    if (directRetVal != null) {
        return directRetVal;
    }/*from w  ww.j av  a  2 s.  c o  m*/

    BaseMethodBinding<?> binding = myBindings.get(theMethod);
    if (binding != null) {
        BaseHttpClientInvocation clientInvocation = binding.invokeClient(theArgs);
        return invokeClient(myContext, binding, clientInvocation);
    }

    ILambda lambda = myMethodToLambda.get(theMethod);
    if (lambda != null) {
        return lambda.handle(this, theArgs);
    }

    throw new UnsupportedOperationException(
            "The method '" + theMethod.getName() + "' in type " + theMethod.getDeclaringClass().getSimpleName()
                    + " has no handler. Did you forget to annotate it with a RESTful method annotation?");
}

From source file:se.crisp.codekvast.agent.daemon.codebase.CodeBaseScanner.java

void findTrackedMethods(CodeBase codeBase, Set<String> packages, Set<String> excludePackages, Class<?> clazz) {
    if (clazz.isInterface()) {
        log.debug("Ignoring interface {}", clazz);
        return;//from   w w  w.  j  av  a2s . c o m
    }

    log.debug("Analyzing {}", clazz);
    MethodAnalyzer methodAnalyzer = codeBase.getConfig().getMethodAnalyzer();
    try {
        Method[] declaredMethods = clazz.getDeclaredMethods();
        Method[] methods = clazz.getMethods();
        Method[] allMethods = new Method[declaredMethods.length + methods.length];
        System.arraycopy(declaredMethods, 0, allMethods, 0, declaredMethods.length);
        System.arraycopy(methods, 0, allMethods, declaredMethods.length, methods.length);

        for (Method method : allMethods) {
            SignatureStatus status = methodAnalyzer.apply(method);

            // Some AOP frameworks (e.g., Guice) push methods from a base class down to subclasses created in runtime.
            // We need to map those back to the original declaring signature, or else the original declared method will look unused.

            MethodSignature thisSignature = SignatureUtils.makeMethodSignature(clazz, method);

            MethodSignature declaringSignature = SignatureUtils.makeMethodSignature(
                    findDeclaringClass(method.getDeclaringClass(), method, packages), method);

            if (shouldExcludeSignature(declaringSignature, excludePackages)) {
                status = SignatureStatus.EXCLUDED_BY_PACKAGE_NAME;
            }
            codeBase.addSignature(thisSignature, declaringSignature, status);
        }

        for (Class<?> innerClass : clazz.getDeclaredClasses()) {
            findTrackedMethods(codeBase, packages, excludePackages, innerClass);
        }
    } catch (NoClassDefFoundError e) {
        log.warn("Cannot analyze {}: {}", clazz, e.toString());
    }
}

From source file:jef.tools.reflect.ClassEx.java

private Method getRealMethod(Method method) {
    Class<?> cls = method.getDeclaringClass();
    if (isCGLibProxy(cls)) {
        try {//from w w w . j  a  v  a2 s .  c om
            return cls.getSuperclass().getMethod(method.getName(), method.getParameterTypes());
        } catch (SecurityException e) {
            LogUtil.exception(e);
        } catch (NoSuchMethodException e) {
            LogUtil.exception(e);
        }
    }
    return method;
}

From source file:eu.qualityontime.commons.MethodUtils.java

/**
 * <p>/*  ww  w .j a va 2 s.com*/
 * Return an accessible method (that is, one that can be invoked via
 * reflection) that implements the specified Method. If no such method can
 * be found, return <code>null</code>.
 * </p>
 *
 * @param clazz
 *            The class of the object
 * @param method
 *            The method that we wish to call
 * @return The accessible method
 * @since 1.8.0
 */
public static Method getAccessibleMethod(Class<?> clazz, Method method) {

    // Make sure we have a method to check
    if (method == null) {
        return null;
    }

    // If the requested method is not public we cannot call it
    if (!Modifier.isPublic(method.getModifiers())) {
        return null;
    }

    boolean sameClass = true;
    if (clazz == null) {
        clazz = method.getDeclaringClass();
    } else {
        sameClass = clazz.equals(method.getDeclaringClass());
        if (!method.getDeclaringClass().isAssignableFrom(clazz)) {
            throw new IllegalArgumentException(
                    clazz.getName() + " is not assignable from " + method.getDeclaringClass().getName());
        }
    }

    // If the class is public, we are done
    if (Modifier.isPublic(clazz.getModifiers())) {
        if (!sameClass && !Modifier.isPublic(method.getDeclaringClass().getModifiers())) {
            setMethodAccessible(method); // Default access superclass
            // workaround
        }
        return method;
    }

    final String methodName = method.getName();
    final Class<?>[] parameterTypes = method.getParameterTypes();

    // Check the implemented interfaces and subinterfaces
    method = getAccessibleMethodFromInterfaceNest(clazz, methodName, parameterTypes);

    // Check the superclass chain
    if (method == null) {
        method = getAccessibleMethodFromSuperclass(clazz, methodName, parameterTypes);
    }

    return method;
}

From source file:com.khs.sherpa.servlet.request.DefaultSherpaRequest.java

protected void hasPermission(Method method, String userid, String token) {
    SessionTokenService service = null;//www.ja  v a2 s  .com
    try {
        service = applicationContext.getManagedBean(SessionTokenService.class);
    } catch (NoSuchManagedBeanExcpetion e) {
        throw new SherpaRuntimeException(e);
    }

    if (method.isAnnotationPresent(DenyAll.class)) {
        throw new SherpaPermissionExcpetion("method [" + method.getName() + "] in class ["
                + method.getDeclaringClass().getCanonicalName() + "] has `@DenyAll` annotation", "DENY_ALL");
    }

    if (method.isAnnotationPresent(RolesAllowed.class)) {
        boolean fail = true;
        for (String role : method.getAnnotation(RolesAllowed.class).value()) {
            if (service.hasRole(userid, token, role)) {
                fail = false;
            }
        }
        if (fail) {
            throw new SherpaPermissionExcpetion("method [" + method.getName() + "] in class ["
                    + method.getDeclaringClass().getCanonicalName() + "] has `@RolesAllowed` annotation",
                    "DENY_ROLE");
        }
    }
}

From source file:grails.plugin.cache.GrailsAnnotationCacheOperationSource.java

protected Collection<CacheOperation> computeCacheOperations(Method method, Class<?> targetClass) {
    // Don't allow no-public methods as required.
    if (publicMethodsOnly && !Modifier.isPublic(method.getModifiers())) {
        return null;
    }/*from  w ww .j a  v a 2s.c  o m*/

    // The method may be on an interface, but we need attributes from the target class.
    // If the target class is null, the method will be unchanged.
    Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
    // If we are dealing with method with generic parameters, find the original method.
    specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);

    // First try is the method in the target class.
    Collection<CacheOperation> opDef = findCacheOperations(specificMethod);
    if (opDef != null) {
        return opDef;
    }

    // Second try is the caching operation on the target class.
    opDef = findCacheOperations(specificMethod.getDeclaringClass());
    if (opDef != null) {
        return opDef;
    }

    if (specificMethod != method) {
        // Fall back is to look at the original method.
        opDef = findCacheOperations(method);
        if (opDef != null) {
            return opDef;
        }
        // Last fall back is the class of the original method.
        return findCacheOperations(method.getDeclaringClass());
    }

    return null;
}

From source file:com.developmentsprint.spring.breaker.annotations.AbstractFallbackCircuitBreakerAttributeSource.java

/**
 * Same signature as {@link #getCircuitBreakerAttribute}, but doesn't cache the result. {@link #getCircuitBreakerAttribute} is effectively a caching
 * decorator for this method.//from  ww w.j  a  v  a 2s . c  o  m
 * 
 * @see #getCircuitBreakerAttribute(Method, Class)
 */
private CircuitBreakerAttribute computeCircuitBreakerAttribute(Method method, Class<?> targetClass) {
    // Don't allow no-public methods as required.
    if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
        return null;
    }

    // Ignore CGLIB subclasses - introspect the actual user class.
    Class<?> userClass = ClassUtils.getUserClass(targetClass);

    // The method may be on an interface, but we need attributes from the target class.
    // If the target class is null, the method will be unchanged.
    Method specificMethod = ClassUtils.getMostSpecificMethod(method, userClass);

    // If we are dealing with method with generic parameters, find the original method.
    specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);

    // First try is the method in the target class.
    CircuitBreakerAttribute cbAttribute = findCircuitBreakerAttribute(specificMethod);
    if (cbAttribute != null) {
        return cbAttribute;
    }

    // Second try is the circuit breaker attribute on the target class.
    cbAttribute = findCircuitBreakerAttribute(specificMethod.getDeclaringClass());
    if (cbAttribute != null) {
        return cbAttribute;
    }

    if (specificMethod != method) {
        // Fallback is to look at the original method.
        cbAttribute = findCircuitBreakerAttribute(method);
        if (cbAttribute != null) {
            return cbAttribute;
        }
        // Last fallback is the class of the original method.
        return findCircuitBreakerAttribute(method.getDeclaringClass());
    }
    return null;
}

From source file:com.haulmont.cuba.core.app.AbstractBeansMetadata.java

protected List<MethodInfo> getAvailableMethods(String beanName) {
    List<MethodInfo> methods = new ArrayList<>();
    try {/*from   w w  w  . j a  v a 2 s .c o m*/
        AutowireCapableBeanFactory beanFactory = AppContext.getApplicationContext()
                .getAutowireCapableBeanFactory();
        if (beanFactory instanceof CubaDefaultListableBeanFactory) {
            BeanDefinition beanDefinition = ((CubaDefaultListableBeanFactory) beanFactory)
                    .getBeanDefinition(beanName);
            if (beanDefinition.isAbstract())
                return methods;
        }

        Object bean = AppBeans.get(beanName);

        @SuppressWarnings("unchecked")
        List<Class> classes = ClassUtils.getAllInterfaces(bean.getClass());
        for (Class aClass : classes) {
            if (aClass.getName().startsWith("org.springframework."))
                continue;

            Class<?> targetClass = bean instanceof TargetClassAware ? ((TargetClassAware) bean).getTargetClass()
                    : bean.getClass();

            for (Method method : aClass.getMethods()) {
                if (isMethodAvailable(method)) {
                    Method targetClassMethod = targetClass.getMethod(method.getName(),
                            method.getParameterTypes());
                    List<MethodParameterInfo> methodParameters = getMethodParameters(targetClassMethod);
                    MethodInfo methodInfo = new MethodInfo(method.getName(), methodParameters);
                    addMethod(methods, methodInfo);
                }
            }

            if (methods.isEmpty()) {
                for (Method method : bean.getClass().getMethods()) {
                    if (!method.getDeclaringClass().equals(Object.class) && isMethodAvailable(method)) {
                        List<MethodParameterInfo> methodParameters = getMethodParameters(method);
                        MethodInfo methodInfo = new MethodInfo(method.getName(), methodParameters);
                        addMethod(methods, methodInfo);
                    }
                }
            }
        }
    } catch (Throwable t) {
        log.debug(t.getMessage());
    }
    return methods;
}