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:org.ff4j.aop.FeatureAdvisor.java

private Object callAlterClazzMethod(final MethodInvocation pMInvoc, Object targetBean, Logger targetLogger)
        throws Throwable {
    Method method = pMInvoc.getMethod();
    String declaringClass = method.getDeclaringClass().getName();
    targetLogger.debug("FeatureFlipping on method:{} class:{}", method.getName(), declaringClass);
    try {/*from  w  w w.jav a  2  s  .  c  o  m*/
        return method.invoke(targetBean, pMInvoc.getArguments());
    } catch (IllegalAccessException e) {
        throw makeIllegalArgumentException("ff4j-aop: Cannot invoke " + method.getName() + " on alterbean "
                + declaringClass + " please check visibility", e);
    } catch (InvocationTargetException invocationTargetException) {
        if (!ff4j.isAlterBeanThrowInvocationTargetException() && invocationTargetException.getCause() != null) {
            throw invocationTargetException.getCause();
        }
        throw makeIllegalArgumentException("ff4j-aop: Cannot invoke " + method.getName() + " on alterbean "
                + declaringClass + " please check signatures", invocationTargetException);
    } catch (Exception exception) {
        throw makeIllegalArgumentException("ff4j-aop: Cannot invoke " + method.getName() + " on alterbean "
                + declaringClass + " please check signatures", exception);
    }
}

From source file:de.tolina.common.validation.AnnotationValidation.java

/**
 * Calls dependent on the type of the given Object:
 * <br> - {@link AnnotationUtils#getAnnotations(Method)} or
 * <br> - {@link AnnotationUtils#getAnnotations(java.lang.reflect.AnnotatedElement)}
 *///from  w  ww  . j a  v a 2  s  .  co  m
@Nullable
private Annotation[] getAllAnnotationsFor(@Nonnull final Object annotated) {
    if (annotated instanceof Field) {
        return getAnnotations((Field) annotated);
    }

    if (annotated instanceof Method) {
        final Method annotatedMethod = (Method) annotated;
        final Class<?> declaringClass = annotatedMethod.getDeclaringClass();
        final List<Class<?>> allClasses = new ArrayList<>();
        allClasses.add(declaringClass);
        allClasses.addAll(ClassUtils.getAllSuperclasses(declaringClass));

        final ArrayList<Annotation> allAnnotations = new ArrayList<>();

        for (final Class<?> aClass : allClasses) {
            final ArrayList<Method> allMethods = new ArrayList<>();
            allMethods.addAll(Arrays.asList(aClass.getDeclaredMethods()));

            final List<Class<?>> interfaces = ClassUtils.getAllInterfaces(aClass);
            for (final Class<?> anInterface : interfaces) {
                allMethods.addAll(Arrays.asList(anInterface.getDeclaredMethods()));
            }

            allMethods.stream().filter(method -> isSameMethod(method, annotatedMethod))
                    .forEachOrdered(method -> addIfNotPresent(allAnnotations, getAnnotations(method)));
        }

        return allAnnotations.toArray(new Annotation[] {});
    }

    final Class<?> annotatedClass = (Class<?>) annotated;
    final List<Class<?>> allClasses = new ArrayList<>();
    allClasses.add(annotatedClass);
    allClasses.addAll(ClassUtils.getAllSuperclasses(annotatedClass));

    final ArrayList<Annotation> allAnnotations = new ArrayList<>();

    for (final Class<?> aClass : allClasses) {
        addIfNotPresent(allAnnotations, getAnnotations(aClass));
        final List<Class<?>> interfaces = ClassUtils.getAllInterfaces(aClass);
        for (final Class<?> anInterface : interfaces) {
            addIfNotPresent(allAnnotations, getAnnotations(anInterface));
        }
    }

    return allAnnotations.toArray(new Annotation[] {});
}

From source file:ca.uhn.fhir.rest.method.ElementsParameter.java

@Override
public void initializeTypes(Method theMethod, Class<? extends Collection<?>> theOuterCollectionType,
        Class<? extends Collection<?>> theInnerCollectionType, Class<?> theParameterType) {
    if (theOuterCollectionType != null) {
        throw new ConfigurationException("Method '" + theMethod.getName() + "' in type '"
                + theMethod.getDeclaringClass().getCanonicalName() + "' is of type " + SummaryEnum.class
                + " but can not be a collection of collections");
    }/*from  w  ww.ja va  2  s. c  om*/
    if (theInnerCollectionType != null) {
        myInnerCollectionType = CollectionBinder.getInstantiableCollectionType(theInnerCollectionType,
                SummaryEnum.class.getSimpleName());
    }
}

From source file:de.otto.jsonhome.generator.HintsGenerator.java

/**
 * Analyses the method with a RequestMapping and returns the corresponding Hints.
 * <p/>//from w  ww.  java2 s  . com
 * If the RequestMapping does not specify the produced or consumed representations,
 * "text/html" is returned in a singleton list. In case of a POST method, the default representation
 * is "application/x-www-form-urlencoded".
 * <p/>
 *
 * @return Hints.
 * @throws NullPointerException if method is not annotated with @RequestMapping.
 */

public final Hints hintsOf(final URI relationType, final Method method) {
    final Set<Allow> allows = allowedHttpMethodsOf(method);
    final HintsBuilder hintsBuilder = hintsBuilder().allowing(allows)
            .with(docsGenerator.documentationFrom(relationType, method.getDeclaringClass()))
            .acceptingRanges(acceptedRangesFrom(method)).preferring(preferencesFrom(method))
            .requiring(preconditionsFrom(method)).withAuthRequired(requiredAuthenticationFrom(method))
            .withStatus(statusFrom(method));

    final List<String> produced = producedRepresentationsOf(method);
    final List<String> consumed = consumedRepresentationsOf(method);
    if (allows.contains(PUT)) {
        hintsBuilder.acceptingForPut(consumed);
        hintsBuilder.representedAs(produced);
    } else if (allows.contains(PATCH)) {
        hintsBuilder.acceptingForPatch(consumed);
        hintsBuilder.representedAs(produced);
    } else if (allows.contains(POST)) {
        hintsBuilder
                .acceptingForPost(consumed.isEmpty() ? asList("application/x-www-form-urlencoded") : consumed);
        hintsBuilder.representedAs(produced);
    } else if (allows.contains(GET) || allows.contains(HEAD)) {
        final List<String> representations = join(produced, consumed);
        hintsBuilder.representedAs(representations.isEmpty() ? asList("text/html") : representations);
    } else {
        hintsBuilder.representedAs(join(produced, consumed));
    }
    return hintsBuilder.build();
}

From source file:cf.spring.servicebroker.ServiceBrokerMethods.java

private void validateBindMethod(Method bindMethod, boolean bindable) {
    if (bindable && bindMethod == null) {
        throw new BeanCreationException(
                "Bindable service brokers must have a method with @" + Bind.class.getName());
    }//from   w  ww.  j a v  a  2 s.c o m
    if (!bindable && bindMethod != null) {
        throw new BeanCreationException("Service broker on class " + bindMethod.getDeclaringClass().getName()
                + " is NOT bindable but has a method annotated with @" + Bind.class.getName());
    }
    if (bindMethod == null) {
        return;
    }
    validateReturnType(bindMethod, Bind.class, BindResponse.class);
    validateArgument(bindMethod, Bind.class, BindRequest.class);
}

From source file:org.apereo.services.persondir.support.AttributeBasedCacheKeyGenerator.java

/**
 * Iterates over the {@link CachableMethod} instances to determine which instance the
 * passed {@link MethodInvocation} applies to.
 *
 * @param methodInvocation method invocation
 * @return Cachable method//w  ww.j a  v a  2  s.co m
 */
protected CachableMethod resolveCacheableMethod(final MethodInvocation methodInvocation) {
    final Method targetMethod = methodInvocation.getMethod();
    final Class<?> targetClass = targetMethod.getDeclaringClass();

    for (final CachableMethod cachableMethod : CachableMethod.values()) {
        Method cacheableMethod = null;
        try {
            cacheableMethod = targetClass.getMethod(cachableMethod.getName(), cachableMethod.getArgs());
        } catch (final SecurityException e) {
            this.logger.warn("Security exception while attempting to if the target class '" + targetClass
                    + "' implements the cachable method '" + cachableMethod + "'", e);
        } catch (final 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.apache.lens.cli.doc.TestGenerateCLIUserDoc.java

@Test
public void generateDoc() throws IOException {
    BufferedWriter bw = new BufferedWriter(new FileWriter(new File(APT_FILE)));
    StringBuilder sb = new StringBuilder();
    sb.append(getCLIIntroduction()).append("\n\n\n");
    List<Class<? extends CommandMarker>> classes = Lists.newArrayList(LensConnectionCommands.class,
            LensDatabaseCommands.class, LensStorageCommands.class, LensCubeCommands.class,
            LensDimensionCommands.class, LensFactCommands.class, LensDimensionTableCommands.class,
            LensNativeTableCommands.class, LensQueryCommands.class, LensLogResourceCommands.class,
            LensSchemaCommands.class);

    for (Class claz : classes) {
        UserDocumentation doc = (UserDocumentation) claz.getAnnotation(UserDocumentation.class);
        if (doc != null && StringUtils.isNotBlank(doc.title())) {
            sb.append("** ").append(doc.title()).append("\n\n  ").append(doc.description()).append("\n\n");
        }/* www.ja  v  a 2 s .  c  o m*/
        sb.append("*--+--+\n" + "|<<Command>>|<<Description>>|\n" + "*--+--+\n");
        TreeSet<Method> methods = Sets.newTreeSet(new Comparator<Method>() {
            @Override
            public int compare(Method o1, Method o2) {
                return o1.getAnnotation(CliCommand.class).value()[0]
                        .compareTo(o2.getAnnotation(CliCommand.class).value()[0]);
            }
        });

        for (Method method : claz.getMethods()) {
            if (method.getAnnotation(CliCommand.class) != null) {
                methods.add(method);
            } else {
                log.info("Not adding " + method.getDeclaringClass().getSimpleName() + "#" + method.getName());
            }
        }
        List<DocEntry> docEntries = Lists.newArrayList();
        for (Method method : methods) {
            CliCommand annot = method.getAnnotation(CliCommand.class);
            StringBuilder commandBuilder = new StringBuilder();
            String sep = "";
            for (String value : annot.value()) {
                commandBuilder.append(sep).append(value);
                sep = "/";
            }
            for (Annotation[] annotations : method.getParameterAnnotations()) {
                for (Annotation paramAnnot : annotations) {
                    if (paramAnnot instanceof CliOption) {
                        CliOption cliOption = (CliOption) paramAnnot;
                        HashSet<String> keys = Sets.newHashSet(cliOption.key());
                        boolean optional = false;
                        if (keys.contains("")) {
                            optional = true;
                            keys.remove("");
                        }
                        if (!keys.isEmpty()) {
                            commandBuilder.append(" ");
                            if (!cliOption.mandatory()) {
                                commandBuilder.append("[");
                            }
                            if (optional) {
                                commandBuilder.append("[");
                            }
                            sep = "";
                            for (String key : keys) {
                                commandBuilder.append(sep).append("--").append(key);
                                sep = "/";
                            }
                            if (optional) {
                                commandBuilder.append("]");
                            }
                            sep = "";
                        }
                        commandBuilder.append(" ")
                                .append(cliOption.help().replaceAll("<", "\\\\<").replaceAll(">", "\\\\>"));
                        if (!cliOption.mandatory()) {
                            commandBuilder.append("]");
                        }
                    }
                }
            }
            docEntries.add(new DocEntry(commandBuilder.toString(),
                    annot.help().replaceAll("<", "<<<").replaceAll(">", ">>>")));
        }
        for (DocEntry entry : docEntries) {
            for (int i = 0; i < entry.getHelp().length; i++) {
                sb.append("|").append(i == 0 ? entry.getCommand() : entry.getCommand().replaceAll(".", " "))
                        .append("|").append(entry.getHelp()[i]).append("|").append("\n");
            }
            sb.append("*--+--+\n");
        }
        sb.append("  <<").append(getReadableName(claz.getSimpleName())).append(">>\n\n===\n\n");
    }
    bw.write(sb.toString());
    bw.close();
}

From source file:com.interface21.aop.framework.AopProxy.java

/**
 * Implementation of InvocationHandler.invoke.
 * Callers will see exactly the exception thrown by the target, unless a hook
 * method throws an exception./* w  w  w.j a va  2  s  . c  o m*/
 */
public final Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

    // Create a new invocation object
    // TODO refactor into InvocationFactory?
    MethodInvocationImpl invocation = new MethodInvocationImpl(proxy, this.config.getTarget(),
            method.getDeclaringClass(), method, args, this.config.getMethodPointcuts(), // could customize here
            this.config.getAttributeRegistry());

    if (this.config.getExposeInvocation()) {
        // Make invocation available if necessary
        AopContext.setCurrentInvocation(invocation);
    }

    try {
        if (EQUALS_METHOD.equals(invocation.getMethod())) {
            // What if equals throws exception!?
            logger.debug("Intercepting equals() method in proxy");
            return invocation.getMethod().invoke(this, invocation.getArguments());
        }

        Object retVal = invocation.proceed();
        if (retVal != null && retVal == invocation.getThis()) {
            // Special case: it returned this
            // Note that we can't help if the target sets
            // a reference to itself in another returned object
            logger.debug("Replacing 'this' with reference to proxy");
            retVal = proxy;
        }
        return retVal;
    } finally {
        if (this.config.getExposeInvocation()) {
            AopContext.setCurrentInvocation(null);
        }
    }
}

From source file:org.apache.openejb.util.proxy.QueryProxy.java

public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
    if (method.getDeclaringClass().equals(Object.class)) {
        return method.invoke(this, args);
    }//from w w w  .  j av a2 s.c  o  m

    final String methodName = method.getName();
    final Class<?> returnType = method.getReturnType();

    // simple cases
    if (PERSIST_NAME.equals(methodName)) {
        persist(args, returnType);
        return null; // void
    }

    if (MERGE_NAME.equals(methodName)) {
        return merge(args, returnType);
    }

    if (REMOVE_NAME.equals(methodName)) {
        remove(args, returnType);
        return null; // void
    }

    // queries
    if (NAMED_QUERY_NAME.equals(methodName)) {
        return query(method, args, QueryType.NAMED);
    }

    if (NATIVE_QUERY_NAME.equals(methodName)) {
        return query(method, args, QueryType.NATIVE);
    }

    if (QUERY_NAME.equals(methodName)) {
        return query(method, args, QueryType.OTHER);
    }

    // finders
    if (methodName.startsWith(FIND_PREFIX)) {
        return find(method, args);
    }

    throw new IllegalArgumentException("method not yet managed");
}

From source file:com.liferay.portal.jsonwebservice.JSONWebServiceConfigurator.java

private void _onJSONWebServiceClass(String className) throws Exception {
    Class<?> actionClass = _classLoader.loadClass(className);

    if (!_isJSONWebServiceClass(actionClass)) {
        return;/*from w  w  w .  j  a  va2s .  com*/
    }

    if (actionClass.isInterface() && _hasAnnotatedServiceImpl(className)) {
        return;
    }

    JSONWebService classAnnotation = actionClass.getAnnotation(JSONWebService.class);

    JSONWebServiceMode classAnnotationMode = JSONWebServiceMode.MANUAL;

    if (classAnnotation != null) {
        classAnnotationMode = classAnnotation.mode();
    }

    Method[] methods = actionClass.getMethods();

    for (Method method : methods) {
        Class<?> methodDeclaringClass = method.getDeclaringClass();

        if (!methodDeclaringClass.equals(actionClass)) {
            continue;
        }

        boolean registerMethod = false;

        JSONWebService methodAnnotation = method.getAnnotation(JSONWebService.class);

        if (classAnnotationMode.equals(JSONWebServiceMode.AUTO)) {
            registerMethod = true;

            if (methodAnnotation != null) {
                JSONWebServiceMode methodAnnotationMode = methodAnnotation.mode();

                if (methodAnnotationMode.equals(JSONWebServiceMode.IGNORE)) {

                    registerMethod = false;
                }
            }
        } else {
            if (methodAnnotation != null) {
                JSONWebServiceMode methodAnnotationMode = methodAnnotation.mode();

                if (!methodAnnotationMode.equals(JSONWebServiceMode.IGNORE)) {

                    registerMethod = true;
                }
            }
        }

        if (registerMethod) {
            _registerJSONWebServiceAction(actionClass, method);
        }
    }
}