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:tv.arte.resteventapi.core.presentation.decoration.RestEventApiDecorationProvider.java

/**
 * Load controller mappings at the end of Spring context init
 *//*from   w  w w  . j ava 2 s  . co m*/
public void onApplicationEvent(ContextRefreshedEvent event) {

    Map<Class<?>, Method> hrefedBeansControllerMethodMapping = new HashMap<Class<?>, Method>();

    Map<String, ?> abstractMethodHandlers = event.getApplicationContext()
            .getBeansOfType(AbstractHandlerMethodMapping.class);
    for (Entry<String, ?> abstractMethodHandler : abstractMethodHandlers.entrySet()) {
        Map<?, HandlerMethod> methods = ((AbstractHandlerMethodMapping<?>) abstractMethodHandler.getValue())
                .getHandlerMethods();
        for (Entry<?, HandlerMethod> handMet : methods.entrySet()) {
            Method method = handMet.getValue().getMethod();
            Hrefed hrefedAnnotation = method.getAnnotation(Hrefed.class);
            if (hrefedAnnotation != null) {
                for (Class<?> hrefedClass : hrefedAnnotation.value()) {
                    if (hrefedBeansControllerMethodMapping.containsKey(hrefedClass)) {
                        throw new RestEventApiRuntimeException("Cannot have " + Hrefed.class.getSimpleName()
                                + " annotation on more that 1 controller handler methods."
                                + " The related Hrefed bean class is: " + hrefedClass
                                + ". The incriminated controller class: "
                                + method.getDeclaringClass().getSimpleName() + ", with method: "
                                + method.getName());
                    }

                    hrefedBeansControllerMethodMapping.put(hrefedClass, method);
                }
            }
        }
    }

    if (hrefedBeansControllerMethodMapping != null && !hrefedBeansControllerMethodMapping.isEmpty()) {
        RestEventApiDecorationProvider.hrefedBeansControllerMethodMapping.clear();
    }
    RestEventApiDecorationProvider.hrefedBeansControllerMethodMapping
            .putAll(hrefedBeansControllerMethodMapping);
}

From source file:org.zkybase.kite.circuitbreaker.interceptor.CircuitBreakerSourcePointcut.java

/**
 * @param method//from  ww  w .  j  a v a  2 s  .c o m
 *            method to evaluate
 * @param targetClass
 *            target class to evaluate (if <code>null</code>, then we
 *            evaluate against the method's declaring class
 * @return boolean indicating whether the target method is eligible for
 *         advice
 */
public boolean matches(Method method, Class<?> targetClass) {
    if (source == null) {
        throw new IllegalStateException("source can't be null");
    }

    // Hm, the existence of a circuit breaker source is actually runtime
    // information, not static. Does that violate the spirit of the
    // StaticMethodMatcher contract? (The contract states explicitly that
    // we won't get runtime info about the method call, but I don't think it
    // says anything about other runtime information...) At any rate, it
    // definitely wouldn't make any sense to declare this as a
    // DynamicMethodMatcherPointcut since the method arguments never matter.
    boolean match = source.getBreaker(method, targetClass) != null;
    if (match) {
        Class<?> clazz = (targetClass != null ? targetClass : method.getDeclaringClass());
        log.debug("Found pointcut match for {}.{}", clazz.getName(), method.getName());
    }
    return match;
}

From source file:com.mycila.plugin.Cglib2AopProxy.java

/**
 * Checks for final methods on the <code>Class</code> and writes warnings to the log
 * for each one found./*from  w  ww. j  a  v  a 2  s. com*/
 */
private void doValidateClass(Class proxySuperClass) {
    Method[] methods = proxySuperClass.getMethods();
    for (Method method : methods) {
        if (!Object.class.equals(method.getDeclaringClass()) && Modifier.isFinal(method.getModifiers())) {
            logger.warn("Unable to proxy method [" + method + "] because it is final: "
                    + "All calls to this method via a proxy will be routed directly to the proxy.");
        }
    }
}

From source file:com.px100systems.util.serialization.SerializationDefinition.java

private Object invokeMethod(Method method, Object bean, Object... args) {
    try {/* w w w .j av a 2  s .c o  m*/
        return method.invoke(bean, args);
    } catch (Exception e) {
        throw new RuntimeException("Method " + method.getDeclaringClass().getSimpleName() + "."
                + method.getName() + " invocation error: " + e.getMessage(), e);
    }
}

From source file:org.apache.cocoon.components.flow.java.JavaInterpreter.java

/**
 * Calls a Java function, passing <code>params</code> as its
 * arguments. In addition to this, it makes available the parameters
 * through the <code>cocoon.parameters</code> Java array
 * (indexed by the parameter names).//from  w  w w. j a v  a 2 s.  c  o  m
 *
 * @param function a <code>String</code> value
 * @param params a <code>List</code> value
 * @param redirector
 * @exception Exception if an error occurs
 */
public void callFunction(String function, List params, Redirector redirector) throws Exception {

    if (!initialized)
        initialize();

    Method method = (Method) methods.get(function);

    if (method == null) {
        throw new ProcessingException("No method '" + function + "' found. " + methods);
    }

    if (getLogger().isDebugEnabled())
        getLogger().debug("calling method \"" + method + "\"");

    Request request = ContextHelper.getRequest(this.avalonContext);
    Session session = request.getSession(true);
    HashMap userScopes = (HashMap) session.getAttribute(USER_GLOBAL_SCOPE);
    if (userScopes == null)
        userScopes = new HashMap();

    Continuable flow = (Continuable) userScopes.get(method.getDeclaringClass());

    ContinuationContext context = new ContinuationContext();
    context.setObject(flow);
    context.setMethod(method);
    context.setAvalonContext(avalonContext);
    context.setLogger(getLogger());
    context.setServiceManager(manager);
    context.setRedirector(redirector);
    Parameters parameters = new Parameters();
    for (Iterator i = params.iterator(); i.hasNext();) {
        Argument argument = (Argument) i.next();
        parameters.setParameter(argument.name, argument.value);
    }
    context.setParameters(parameters);

    Continuation continuation = new Continuation(context);

    WebContinuation wk = continuationsMgr.createWebContinuation(continuation, null, timeToLive,
            getInterpreterID(), null);
    FlowHelper.setWebContinuation(ContextHelper.getObjectModel(this.avalonContext), wk);

    continuation.registerThread();
    try {
        if (flow == null) {
            if (getLogger().isDebugEnabled())
                getLogger().debug("create new instance of \"" + method.getDeclaringClass() + "\"");

            flow = (Continuable) method.getDeclaringClass().newInstance();
            context.setObject(flow);
        }

        method.invoke(flow, new Object[0]);

    } catch (InvocationTargetException ite) {
        if (ite.getTargetException() != null) {
            if (ite.getTargetException() instanceof Exception)
                throw (Exception) ite.getTargetException();
            else if (ite.getTargetException() instanceof Error)
                throw new ProcessingException("An internal error occured", ite.getTargetException());
            else if (ite.getTargetException() instanceof RuntimeException)
                throw (RuntimeException) ite.getTargetException();
            else
                throw ite;
        } else {
            throw ite;
        }
    } finally {
        // remove last object reference, which is not needed to
        // reconstruct the invocation path
        if (continuation.isCapturing())
            continuation.getStack().popReference();
        continuation.deregisterThread();
    }
    userScopes.put(method.getDeclaringClass(), flow);
    session.setAttribute(USER_GLOBAL_SCOPE, userScopes);
}

From source file:ch.digitalfondue.npjt.QueryFactory.java

@SuppressWarnings("unchecked")
public <T> T from(final Class<T> clazz) {

    return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, new InvocationHandler() {
        @Override/*  www .  j  a  v  a 2  s .  co m*/
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            boolean hasAnnotation = method.getAnnotation(Query.class) != null;
            if (hasAnnotation) {
                QueryTypeAndQuery qs = extractQueryAnnotation(clazz, method);
                return qs.type.apply(qs.query, qs.rowMapperClass, jdbc, method, args, columnMapperFactories.set,
                        parameterConverters.set);
            } else if (method.getReturnType().equals(NamedParameterJdbcTemplate.class) && args == null) {
                return jdbc;
            } else if (IS_DEFAULT_METHOD != null && (boolean) IS_DEFAULT_METHOD.invoke(method)) {
                final Class<?> declaringClass = method.getDeclaringClass();
                return LOOKUP_CONSTRUCTOR.newInstance(declaringClass, MethodHandles.Lookup.PRIVATE)
                        .unreflectSpecial(method, declaringClass).bindTo(proxy).invokeWithArguments(args);
            } else {
                throw new IllegalArgumentException(
                        String.format("missing @Query annotation for method %s in interface %s",
                                method.getName(), clazz.getSimpleName()));
            }

        }
    }

    );
}

From source file:org.openmrs.module.webservices.rest.web.DelegatingCrudResourceTest.java

/**
 * This test looks at all subclasses of DelegatingCrudResource, and test all {@link RepHandler}
 * methods to make sure they are all capable of running without exceptions. It also checks that
 *//*from   ww w.ja  v  a2  s . c o  m*/
@SuppressWarnings("rawtypes")
@Test
@Ignore
public void testAllReprsentationDescriptions() throws Exception {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            true);
    //only match subclasses of BaseDelegatingResource
    provider.addIncludeFilter(new AssignableTypeFilter(BaseDelegatingResource.class));

    // scan in org.openmrs.module.webservices.rest.web.resource package 
    Set<BeanDefinition> components = provider
            .findCandidateComponents("org.openmrs.module.webservices.rest.web.resource");
    if (CollectionUtils.isEmpty(components))
        Assert.fail("Faile to load any resource classes");

    for (BeanDefinition component : components) {
        Class resourceClass = Class.forName(component.getBeanClassName());
        for (Method method : ReflectionUtils.getAllDeclaredMethods(resourceClass)) {
            ParameterizedType parameterizedType = (ParameterizedType) resourceClass.getGenericSuperclass();
            Class openmrsClass = (Class) parameterizedType.getActualTypeArguments()[0];
            //User Resource is special in that the Actual parameterized Type isn't a standard domain object, so we also
            //need to look up fields and methods from the org.openmrs.User class 
            boolean isUserResource = resourceClass.equals(UserResource1_8.class);
            List<Object> refDescriptions = new ArrayList<Object>();

            if (method.getName().equals("getRepresentationDescription")
                    && method.getDeclaringClass().equals(resourceClass)) {
                //get all the rep definitions for all representations
                refDescriptions
                        .add(method.invoke(resourceClass.newInstance(), new Object[] { Representation.REF }));
                refDescriptions.add(
                        method.invoke(resourceClass.newInstance(), new Object[] { Representation.DEFAULT }));
                refDescriptions
                        .add(method.invoke(resourceClass.newInstance(), new Object[] { Representation.FULL }));
            }

            for (Object value : refDescriptions) {
                if (value != null) {
                    DelegatingResourceDescription des = (DelegatingResourceDescription) value;
                    for (String key : des.getProperties().keySet()) {
                        if (!key.equals("uri") && !key.equals("display") && !key.equals("auditInfo")) {
                            boolean hasFieldOrPropertySetter = (ReflectionUtils.findField(openmrsClass,
                                    key) != null);
                            if (!hasFieldOrPropertySetter) {
                                hasFieldOrPropertySetter = hasSetterMethod(key, resourceClass);
                                if (!hasFieldOrPropertySetter && isUserResource)
                                    hasFieldOrPropertySetter = (ReflectionUtils.findField(User.class,
                                            key) != null);
                            }
                            if (!hasFieldOrPropertySetter)
                                hasFieldOrPropertySetter = hasSetterMethod(key, resourceClass);

                            //TODO replace this hacky way that we are using to check if there is a get method for a 
                            //collection that has no actual getter e.g activeIdentifers and activeAttributes for Patient
                            if (!hasFieldOrPropertySetter) {
                                hasFieldOrPropertySetter = (ReflectionUtils.findMethod(openmrsClass,
                                        "get" + StringUtils.capitalize(key)) != null);
                                if (!hasFieldOrPropertySetter && isUserResource)
                                    hasFieldOrPropertySetter = (ReflectionUtils.findMethod(User.class,
                                            "get" + StringUtils.capitalize(key)) != null);
                            }

                            if (!hasFieldOrPropertySetter)
                                hasFieldOrPropertySetter = isallowedMissingProperty(resourceClass, key);

                            Assert.assertTrue(
                                    "No property found for '" + key + "' for " + openmrsClass
                                            + " nor setter method on resource " + resourceClass,
                                    hasFieldOrPropertySetter);
                        }
                    }
                }
            }
        }
    }
}

From source file:com.bstek.dorado.idesupport.initializer.CommonRuleTemplateInitializer.java

protected List<AutoChildTemplate> getChildTemplates(RuleTemplate ruleTemplate, TypeInfo typeInfo,
        XmlNodeInfo xmlNodeInfo, InitializerContext initializerContext) throws Exception {
    List<AutoChildTemplate> childTemplates = new ArrayList<AutoChildTemplate>();
    if (xmlNodeInfo != null) {
        for (XmlSubNode xmlSubNode : xmlNodeInfo.getSubNodes()) {
            TypeInfo propertyTypeInfo = TypeInfo.parse(xmlSubNode.propertyType());
            List<AutoChildTemplate> childRulesBySubNode = getChildTemplatesBySubNode(ruleTemplate, typeInfo,
                    xmlSubNode.propertyName(), xmlSubNode, propertyTypeInfo, initializerContext);
            if (childRulesBySubNode != null) {
                childTemplates.addAll(childRulesBySubNode);
            }//from   w  w w  .j a  v  a  2 s  .co m
        }
    }

    Class<?> type = typeInfo.getType();
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(type);
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        Method readMethod = propertyDescriptor.getReadMethod();
        if (readMethod != null) {
            if (readMethod.getDeclaringClass() != type) {
                try {
                    readMethod = type.getDeclaredMethod(readMethod.getName(), readMethod.getParameterTypes());
                } catch (NoSuchMethodException e) {
                    continue;
                }
            }

            List<AutoChildTemplate> childTemplatesBySubNode = null;
            XmlSubNode xmlSubNode = readMethod.getAnnotation(XmlSubNode.class);
            if (xmlSubNode != null) {
                TypeInfo propertyTypeInfo;
                Class<?> propertyType = propertyDescriptor.getPropertyType();
                if (Collection.class.isAssignableFrom(propertyType)) {
                    propertyTypeInfo = TypeInfo.parse((ParameterizedType) readMethod.getGenericReturnType(),
                            true);
                    propertyType = propertyTypeInfo.getType();
                } else {
                    propertyTypeInfo = new TypeInfo(propertyType, false);
                }

                childTemplatesBySubNode = getChildTemplatesBySubNode(ruleTemplate, typeInfo,
                        propertyDescriptor.getName(), xmlSubNode, propertyTypeInfo, initializerContext);
            }

            if (childTemplatesBySubNode != null) {
                IdeSubObject ideSubObject = readMethod.getAnnotation(IdeSubObject.class);
                if (ideSubObject != null && !ideSubObject.visible()) {
                    for (AutoChildTemplate childTemplate : childTemplatesBySubNode) {
                        childTemplate.setVisible(false);
                    }
                }
                childTemplates.addAll(childTemplatesBySubNode);
            }
        }
    }
    return childTemplates;
}

From source file:com.github.jinahya.sql.database.metadata.bind.MetadataContext.java

private Set<String> getMethodNames() {

    if (methodNames == null) {
        methodNames = new HashSet<String>();
        for (final Method method : DatabaseMetaData.class.getMethods()) {
            if (method.getDeclaringClass() != DatabaseMetaData.class) {
                continue;
            }/*from   w w  w  . j  a  v  a  2s.co  m*/
            final int modifier = method.getModifiers();
            if (Modifier.isStatic(modifier)) {
                continue;
            }
            if (!Modifier.isPublic(modifier)) {
                continue;
            }
            methodNames.add(method.getName());
        }
    }

    return methodNames;
}

From source file:com.quirklabs.authorise.ProxyAwareLocalVariableTableParameterNameDiscoverer.java

public String[] getParameterNames(Method method) {
    String[] paramNames = this.parameterNamesCache.get(method);

    if (paramNames == null) {
        try {/*from ww  w  . j a v  a2 s .co m*/
            paramNames = visitMethod(method).getParameterNames();
            if (paramNames != null) {
                this.parameterNamesCache.put(method, paramNames);
            }
        } catch (IOException ex) {
            // We couldn't load the class file, which is not fatal as it
            // simply means this method of discovering parameter names won't work.
            if (logger.isDebugEnabled()) {
                logger.debug("IOException whilst attempting to read '.class' file for class ["
                        + method.getDeclaringClass().getName()
                        + "] - unable to determine parameter names for method: " + method, ex);
            }
        }
    }
    return paramNames;
}