Example usage for java.lang Class getAnnotation

List of usage examples for java.lang Class getAnnotation

Introduction

In this page you can find the example usage for java.lang Class getAnnotation.

Prototype

@SuppressWarnings("unchecked")
public <A extends Annotation> A getAnnotation(Class<A> annotationClass) 

Source Link

Usage

From source file:org.jsonschema2pojo.integration.config.CustomAnnotatorIT.java

@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void customAnnotatorIsAbleToAddCustomAnnotations()
        throws ClassNotFoundException, SecurityException, NoSuchMethodException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile(
            "/schema/properties/primitiveProperties.json", "com.example", config("annotationStyle", "none", // turn off core annotations
                    "customAnnotator", DeprecatingAnnotator.class.getName()));

    Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties");

    Method getter = generatedType.getMethod("getA");

    assertThat(generatedType.getAnnotation(Deprecated.class), is(notNullValue()));
    assertThat(generatedType.getAnnotation(Deprecated.class), is(notNullValue()));
    assertThat(getter.getAnnotation(Deprecated.class), is(notNullValue()));
}

From source file:de.ks.activity.context.ActivityContext.java

protected Pair<String, Class<?>> getKey(Bean<?> bean) {
    Class<?> beanClass = bean.getBeanClass();
    Annotation annotation = beanClass.getAnnotation(ActivityScoped.class);

    if (annotation == null) {//might be a producer method, only warn

        String msg = "Unable to retrieve " + ActivityScoped.class.getName() + " from " + beanClass;
        if (bean.getClass().getName().contains("Producer")) {
            log.trace(msg);// ww w.j  a  va 2 s  .c  o  m
        } else {
            log.warn(msg);
        }
    }
    if (currentActivity == null) {
        throw new IllegalStateException("No activity currently active!");
    }
    return Pair.of(currentActivity, beanClass);
}

From source file:com.google.api.ads.adwords.awreporting.model.csv.CsvReportEntitiesMapping.java

/**
 * Checks for the annotation that maps the bean to a CSV file report.
 *
 * @param metadataReader the meta data reader for the bean class.
 * @return true if the {@code CsvReport} annotation is present and the bean class is a sub class
 *         of {@code Report}.//from   www  .j a v a 2  s .co m
 */
private boolean isAnnotationPresentAndReportSubclass(MetadataReader metadataReader) {

    String className = metadataReader.getClassMetadata().getClassName();
    try {
        Class<?> beanClass = Class.forName(className);
        if (beanClass.getAnnotation(CsvReport.class) != null && this.isReportSubclass(beanClass)) {
            return true;
        }
    } catch (ClassNotFoundException e) {
        LOGGER.warning("Class not found in classpath: " + className);
    }
    return false;
}

From source file:net.daum.clix.springframework.data.rest.client.repository.RestRepositories.java

/**
 * Returns the {@link RestResource} for the given domain class's repository.
 * //from w  ww. j a v a 2s  . co m
 * @param domainCall
 *            must not be {@literal null}.
 * @return the {@link RestResource} for the given domain class or
 *         {@literal null} if no @RestResource presents.
 */
public RestResource getRestResourceAnnotationFor(Class<?> domainClass) {
    Class<?> repositoryInterface = getRepositoryInterfaceFor(domainClass);
    return repositoryInterface == null ? null : repositoryInterface.getAnnotation(RestResource.class);
}

From source file:org.jsonschema2pojo.integration.config.CustomAnnotatorIT.java

@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void customAnnotatorCanBeAppliedAlongsideCoreAnnotator()
        throws ClassNotFoundException, SecurityException, NoSuchMethodException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile(
            "/schema/properties/primitiveProperties.json", "com.example",
            config("customAnnotator", DeprecatingAnnotator.class.getName()));

    Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties");

    Method getter = generatedType.getMethod("getA");

    assertThat(generatedType.getAnnotation(JsonPropertyOrder.class), is(notNullValue()));
    assertThat(generatedType.getAnnotation(JsonInclude.class), is(notNullValue()));
    assertThat(getter.getAnnotation(JsonProperty.class), is(notNullValue()));

    assertThat(generatedType.getAnnotation(Deprecated.class), is(notNullValue()));
    assertThat(generatedType.getAnnotation(Deprecated.class), is(notNullValue()));
    assertThat(getter.getAnnotation(Deprecated.class), is(notNullValue()));
}

From source file:com.github.lightdocs.ModelBuilder.java

/**
 * Traverses each method annotations checking if it is annotated with the
 * JAXRS HttpMethod annotation./*w  ww .j  av a  2 s  .  c  o  m*/
 * 
 * @param method
 *            required.
 * @return null if not found
 */
private javax.ws.rs.HttpMethod findJAXRSHttpMethodAnnotation(Method method) {
    // all GET/POST/etc JAXRS annotations have the HttpMethod JAXRS
    // annotation on them
    for (Annotation a : method.getAnnotations()) {
        Class<? extends Annotation> aType = a.annotationType();
        if (aType.isAnnotationPresent(javax.ws.rs.HttpMethod.class)) {
            return aType.getAnnotation(javax.ws.rs.HttpMethod.class);
        }
    }
    return null;
}

From source file:name.ikysil.beanpathdsl.codegen.Context.java

private <A extends Annotation> Map<Class<?>, A> scanForAnnotation(Class<A> annotationClass) {
    Map<Class<?>, A> result = new HashMap<>();
    Set<Class<?>> types = reflections.getTypesAnnotatedWith(annotationClass);
    for (Class<?> type : types) {
        result.put(resolveClass(type), type.getAnnotation(annotationClass));
    }/*from   www.  j  ava  2s. c  o  m*/
    Set<Field> fields = reflections.getFieldsAnnotatedWith(annotationClass);
    for (Field field : fields) {
        result.put(resolveClass(field.getType()), field.getAnnotation(annotationClass));
    }
    Set<Method> methods = reflections.getMethodsAnnotatedWith(annotationClass);
    for (Method method : methods) {
        scanMethod(result, method, annotationClass);
    }
    methods = reflections.getMethodsWithAnyParamAnnotated(annotationClass);
    for (Method method : methods) {
        scanMethod(result, method, annotationClass);
    }
    return result;
}

From source file:adalid.core.ProcessOperation.java

private void annotateProcessOperationClass(Class<?> type) {
    Class<?> annotatedClass = XS1.getAnnotatedClass(type, ProcessOperationClass.class);
    if (annotatedClass != null) {
        ProcessOperationClass annotation = annotatedClass.getAnnotation(ProcessOperationClass.class);
        if (annotation != null) {
            String name = annotation.name();
            if (StringUtils.isNotBlank(name)) {
                _processName = name;// www .java 2  s.c om
            }
            String group = annotation.processingGroup();
            if (StringUtils.isNotBlank(group)) {
                if (StrUtils.esIdentificadorSqlValido(group)) {
                    if (group.length() <= Constants.DEFAULT_CHARACTER_KEY_MAX_LENGTH) {
                        _processingGroup = group;
                        TLC.getProject().getProcessingGroups().add(group);
                    } else {
                        String message = "invalid processing group identifier \"" + group + "\" at "
                                + getFullName();
                        message += "; identifier length cannot be greater than "
                                + Constants.DEFAULT_CHARACTER_KEY_MAX_LENGTH;
                        logger.error(message);
                        TLC.getProject().getParser().increaseErrorCount();
                    }
                } else {
                    String message = "invalid processing group identifier \"" + group + "\" at "
                            + getFullName();
                    logger.error(message);
                    TLC.getProject().getParser().increaseErrorCount();
                }
            }
            _overloading = annotation.overloading();
            _annotatedWithProcessOperationClass = true;
        }
    }
}

From source file:org.fornax.cartridges.sculptor.framework.event.annotation.SubscribeBeanPostProcessor.java

Subscribe getAnnotation(Class<?> clazz) {
    if (clazz == null || clazz == Object.class) {
        return null;
    }/*from w  ww  .j av  a  2 s  .c o m*/
    boolean foundIt = clazz.isAnnotationPresent(Subscribe.class);
    if (foundIt) {
        return clazz.getAnnotation(Subscribe.class);
    }
    // recursive call with super class
    return getAnnotation(clazz.getSuperclass());

}

From source file:com.doitnext.http.router.DefaultEndpointResolver.java

private void addEndpointsToResult(String pathPrefix, Class<?> classz, TreeSet<Route> routes) {
    RestCollection resource = classz.getAnnotation(RestCollection.class);
    StringBuilder pathBuilder = new StringBuilder(pathPrefix);
    pathBuilder.append(resource.pathprefix());

    String resourcePathPrefix = pathBuilder.toString();
    @SuppressWarnings("unchecked")
    Set<Method> methods = ReflectionUtils.getAllMethods(classz,
            ReflectionUtils.withAnnotation(RestMethod.class));

    if (logger.isDebugEnabled())
        logger.debug(String.format("Creating routes for %d methods in %s", methods.size(), classz.getName()));
    for (Method method : methods) {
        if (logger.isDebugEnabled())
            logger.debug(String.format("Attempting to create route for method %s", method.getName()));
        RestMethod methodImpl = method.getAnnotation(RestMethod.class);
        pathBuilder = new StringBuilder(resourcePathPrefix);
        pathBuilder.append(methodImpl.template());
        Object implInstance = applicationContext.getBean(resource.value(), classz);
        RequestResponseContext rrCtx = new RequestResponseContext(
                new InheritableValue(resource.requestType(), methodImpl.requestType()),
                new InheritableValue(resource.returnType(), methodImpl.returnType()),
                new InheritableValue(resource.requestFormat(), methodImpl.requestFormat()),
                new InheritableValue(resource.returnFormat(), methodImpl.returnFormat()));

        addMethodToRoutes(pathBuilder.toString(), implInstance, rrCtx, method, classz, methodImpl.method(),
                routes);//from  ww w .j av a2 s .  c  o m
    }

    // Add dump routes to the set
    if (endpointDumper != null) {
        for (String returnFormat : endpointDumper.getReturnFormats()) {
            pathBuilder = new StringBuilder("endpoints_");
            Object implInstance = this;
            RequestResponseContext rrCtx = new RequestResponseContext(new InheritableValue("", ""),
                    new InheritableValue("", ""), new InheritableValue("", ""),
                    new InheritableValue(returnFormat, returnFormat));
            try {
                Method method = endpointDumper.getClass().getMethod("dumpEndpoints", HttpServletRequest.class,
                        HttpServletResponse.class);
                addMethodToRoutes(pathBuilder.toString(), implInstance, rrCtx, method,
                        endpointDumper.getClass(), HttpMethod.GET, routes);
            } catch (SecurityException e) {
                logger.error("Unable to add endpoint dump", e);
            } catch (NoSuchMethodException e) {
                logger.error("Unable to add endpoint dump", e);
            }
        }
    }
}