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:com.helpinput.spring.registinerceptor.ProxybeanRegistInterceptor.java

@Override
public BeanDefinition beforeRegist(Class<?> clz, String beanName, String scope, DefaultListableBeanFactory dlbf,
        BeanDefinitionBuilder builder) {
    BeanDefinition bd = null;/*from w  ww  .  jav  a2s.  c om*/

    if (getCondition(clz)) {
        Parent ann = clz.getAnnotation(Parent.class);
        String parentName = ann.value();
        String property = ann.property();
        if (Utils.hasLength(parentName) && Utils.hasLength(property)) {

            BeanDefinition parent = (GenericBeanDefinition) dlbf.getBeanDefinition(parentName);
            if (parent != null) {
                String baseBeanName = beanName + "$$$$";
                BeanRegister.removeBean(dlbf, null, baseBeanName);
                BeanDefinition basebd = builder.getBeanDefinition();
                basebd.setScope(scope);
                dlbf.registerBeanDefinition(baseBeanName, basebd);

                bd = new GenericBeanDefinition();

                bd.setParentName(parentName);
                List<PropertyValue> propertyValueList = bd.getPropertyValues().getPropertyValueList();
                RuntimeBeanReference reference = new RuntimeBeanReference(baseBeanName);
                PropertyValue pValue = new PropertyValue(property, reference);
                propertyValueList.add(pValue);

                //dlbf.getBean(baseBeanName);
                return bd;
            }
        }
    }
    return null;
}

From source file:com.googlecode.jsfFlex.renderkit.annotationDocletParser.AnnotationDocletParser15Impl.java

@SuppressWarnings("unchecked")
public void mapComponentFields(Class<? extends Renderer> mapClass, final Object componentObj,
        final String replaceMappingXML) {

    IJsfFlexAttributeProperties jsfFlexAttributeList = IJsfFlexAttributeProperties.class
            .cast(mapClass.getAnnotation(IJsfFlexAttributeProperties.class));

    IJsfFlexAttribute[] jsfFlexAttributes = jsfFlexAttributeList.jsfFlexAttributes();

    for (IJsfFlexAttribute currAttribute : jsfFlexAttributes) {

        FLEX_MAPPER currMapper = currAttribute.byMethod() ? FLEX_MAPPER.FLEX_METHOD_MAPPER
                : FLEX_MAPPER.FLEX_ATTRIBUTE_MAPPER;

        try {//from  w  w  w  .  jav  a 2s  . c om
            TokenValue tokenValue = currMapper.mapField(currAttribute.attribute(), componentObj);
            if (tokenValue != null) {
                getTokenValueSet().add(tokenValue);
            }
        } catch (ComponentBuildException _componentBuildExcept) {
            _log.debug("Exception thrown for [ Class : " + componentObj.getClass().getName()
                    + ", replaceToken : " + currAttribute.attribute() + " ] ");
        }

    }

}

From source file:com.haulmont.cuba.core.sys.persistence.PersistenceConfigProcessor.java

private void addClasses(Element puElem, Map<String, String> classes) {
    for (Element element : Dom4j.elements(puElem, "class")) {
        String className = element.getText();
        Class<Object> cls = ReflectionHelper.getClass(className);
        Entity annotation = cls.getAnnotation(Entity.class);
        if (annotation != null) {
            classes.put(annotation.name(), className);
        } else {// w ww. ja  va  2 s.c om
            classes.put(className, className);
        }
    }
}

From source file:com.googlecode.jsonschema2pojo.integration.config.AnnotationStyleIT.java

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

    ClassLoader resultsClassLoader = generateAndCompile("/schema/properties/primitiveProperties.json",
            "com.example");

    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()));
}

From source file:com.googlecode.jsonschema2pojo.integration.config.AnnotationStyleIT.java

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

    ClassLoader resultsClassLoader = generateAndCompile("/schema/properties/primitiveProperties.json",
            "com.example", config("annotationStyle", "jackson"));

    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()));
}

From source file:com.googlecode.jsonschema2pojo.integration.config.AnnotationStyleIT.java

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

    ClassLoader resultsClassLoader = generateAndCompile("/schema/properties/primitiveProperties.json",
            "com.example", config("annotationStyle", "none"));

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

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

    assertThat(generatedType.getAnnotation(JsonPropertyOrder.class), is(nullValue()));
    assertThat(generatedType.getAnnotation(JsonSerialize.class), is(nullValue()));
    assertThat(getter.getAnnotation(JsonProperty.class), is(nullValue()));

}

From source file:com.github.helenusdriver.commons.lang3.reflect.ReflectionUtils.java

/**
 * Gets annotations that are associated with the specified element. If there
 * are no annotations associated with the element, the return value is an
 * empty map. The difference between this method and
 * {@link AnnotatedElement#getAnnotationsByType(Class)} is that this method
 * works on annotation classes that are annotated with the {@link Keyable}
 * annotation in order to determine the key of each annotation. For this to
 * work, the annotated class must defined a key element as defined in the
 * {@link Keyable} annotation of the same return type as specified in
 * <code>keyClass</code>. If its argument is a repeatable annotation type
 * (JLS 9.6), this method, attempts to find one or more annotations of that
 * type by "looking through" a container annotation. The caller of this method
 * is free to modify the returned map; it will have no effect on the maps
 * returned to other callers./*  ww w . j a  va 2  s  .co m*/
 * <p>
 * This method will look for both the specified annotation and if the
 * annotation is annotated with {@link Repeatable}, it will also look for this
 * containing annotation which must have a <code>value()</code>
 * element with an array type of the specified annotation. The resulting
 * array will always start with the annotation itself if found followed by
 * all of those provided by the containing annotation.
 *
 * @author paouelle
 *
 * @param <K> the type of the keys to find
 * @param <T> the type of the annotation to query for and return if present
 *
 * @param  keyClass the class of the keys to find and return
 * @param  annotationClass the type of annotations to retrieve
 * @param  annotatedElement the element from which to retrieve the annotations
 * @return a non-<code>null</code> ordered map of annotations associated with the
 *         given element properly keyed as defined in each annotation (may be
 *         empty if none found)
 * @throws NullPointerException if <code>annotatedElement</code>,
 *         <code>annotationClass</code> or <code>keyClass</code> is
 *         <code>null</code>
 * @throws IllegalArgumentException if <code>annotationClass</code> is not
 *         annotated with {@link Keyable} or if the containing annotation
 *         doesn't define a <code>value()</code> element returning an array
 *         of type <code>annotationClass</code> or if <code>annotationClass</code>
 *         doesn't define an element named as specified in its {@link Keyable}
 *         annotation that returns a value of the same class as <code>keyClass</code>
 *         or again if a duplicated keyed annotation is found
 */
@SuppressWarnings("unchecked")
public static <K, T extends Annotation> Map<K, T> getAnnotationsByType(Class<K> keyClass,
        Class<T> annotationClass, AnnotatedElement annotatedElement) {
    org.apache.commons.lang3.Validate.notNull(annotationClass, "invalid null annotation class");
    org.apache.commons.lang3.Validate.notNull(annotatedElement, "invalid null annotation element");
    org.apache.commons.lang3.Validate.notNull(keyClass, "invalid null key class");
    final Keyable k = annotationClass.getAnnotation(Keyable.class);

    org.apache.commons.lang3.Validate.isTrue(k != null, "annotation @%s not annotated with @Keyable",
            annotationClass.getName());
    final Method km;

    try {
        km = annotationClass.getMethod(k.value());
    } catch (NoSuchMethodException e) {
        throw new IllegalArgumentException(
                "annotation key element @" + annotationClass.getName() + "." + k.value() + "() not found", e);
    }
    org.apache.commons.lang3.Validate.isTrue(keyClass.isAssignableFrom(km.getReturnType()),
            "annotation key element @%s.%s() doesn't return class: %s", annotationClass.getName(), k.value(),
            keyClass.getName());
    final T[] as = annotatedElement.getAnnotationsByType(annotationClass);

    if (as.length == 0) {
        return Collections.emptyMap();
    }
    final Map<K, T> map = new LinkedHashMap<>(as.length);

    for (T a : as) {
        final K ak;

        try {
            ak = (K) km.invoke(a);
        } catch (IllegalAccessException e) { // not expected
            throw new IllegalStateException(e);
        } catch (InvocationTargetException e) {
            final Throwable t = e.getTargetException();

            if (t instanceof Error) {
                throw (Error) t;
            } else if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else { // not expected
                throw new IllegalStateException(e);
            }
        }
        org.apache.commons.lang3.Validate.isTrue(map.put(ak, a) == null,
                "duplicate key '%s' found in annotation @%s", ak, annotationClass.getName());
    }
    return map;
}

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

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

    ClassLoader resultsClassLoader = schemaRule
            .generateAndCompile("/schema/properties/primitiveProperties.json", "com.example");

    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()));
}

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

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

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile(
            "/schema/properties/primitiveProperties.json", "com.example", config("annotationStyle", "jackson"));

    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()));
}

From source file:com.azaptree.services.spring.application.config.SpringApplicationServiceConfig.java

private void loadConfigurationClasses(final SpringApplicationService config) throws ClassNotFoundException {
    final ConfigurationClasses configurationClasses = config.getConfigurationClasses();
    if (configurationClasses != null && !CollectionUtils.isEmpty(configurationClasses.getClazz())) {
        final ClassLoader cl = getClass().getClassLoader();
        final List<Class<?>> configClasses = new ArrayList<>(configurationClasses.getClazz().size());
        for (final String clazz : configurationClasses.getClazz()) {
            final Class<?> c = cl.loadClass(clazz.trim());
            if (c.getAnnotation(Configuration.class) == null) {
                throw new IllegalArgumentException(String.format(
                        "Class must be annotated with @org.springframework.context.annotation.Configuration: {}",
                        clazz));/*from w ww .j a  va  2s.  c o  m*/
            }
            configClasses.add(c);
        }
        this.configurationClasses = configClasses.toArray(new Class<?>[configClasses.size()]);
    }

}