Example usage for java.lang.reflect AnnotatedElement getDeclaredAnnotations

List of usage examples for java.lang.reflect AnnotatedElement getDeclaredAnnotations

Introduction

In this page you can find the example usage for java.lang.reflect AnnotatedElement getDeclaredAnnotations.

Prototype

Annotation[] getDeclaredAnnotations();

Source Link

Document

Returns annotations that are directly present on this element.

Usage

From source file:com.springframework.core.annotation.AnnotationUtils.java

/**
 * Perform the search algorithm for {@link #findAnnotation(AnnotatedElement, Class)}
 * avoiding endless recursion by tracking which annotations have already
 * been <em>visited</em>.//  w ww  .j a v  a2s .c o m
 * @param annotatedElement the {@code AnnotatedElement} on which to find the annotation
 * @param annotationType the annotation type to look for, both locally and as a meta-annotation
 * @param visited the set of annotations that have already been visited
 * @return the matching annotation, or {@code null} if not found
 * @since 4.2
 */
@SuppressWarnings("unchecked")
private static <A extends Annotation> A findAnnotation(AnnotatedElement annotatedElement,
        Class<A> annotationType, Set<Annotation> visited) {
    Assert.notNull(annotatedElement, "AnnotatedElement must not be null");
    try {
        Annotation[] anns = annotatedElement.getDeclaredAnnotations();
        for (Annotation ann : anns) {
            if (ann.annotationType().equals(annotationType)) {
                return (A) ann;
            }
        }
        for (Annotation ann : anns) {
            if (!isInJavaLangAnnotationPackage(ann) && visited.add(ann)) {
                A annotation = findAnnotation((AnnotatedElement) ann.annotationType(), annotationType, visited);
                if (annotation != null) {
                    return annotation;
                }
            }
        }
    } catch (Exception ex) {
        // Assuming nested Class values not resolvable within annotation attributes...
        logIntrospectionFailure(annotatedElement, ex);
    }
    return null;
}

From source file:com.qrmedia.pattern.compositeannotation.CompositeAnnotatedElements.java

private Set<Class<? extends Annotation>> getCompositeAnnotationTypes(AnnotatedElement annotatedElement,
        boolean includeInherited) {
    Annotation[] annotations = (includeInherited ? annotatedElement.getAnnotations()
            : annotatedElement.getDeclaredAnnotations());
    Set<Class<? extends Annotation>> compositeAnnotations = new HashSet<Class<? extends Annotation>>();

    // collect all the annotations that are annotated with @CompositeAnnotation
    for (Annotation annotation : annotations) {
        Class<? extends Annotation> annotationType = annotation.annotationType();

        if (compositeAnnotationTypeDescriptors.containsKey(annotationType)) {
            compositeAnnotations.add(annotationType);
        }//from   w w w.j  a va2 s  . c  om

    }

    return compositeAnnotations;
}

From source file:com.agimatec.validation.jsr303.Jsr303MetaBeanFactory.java

private boolean processAnnotations(MetaProperty prop, Class owner, AnnotatedElement element,
        AccessStrategy access, AppendValidation appender)
        throws IllegalAccessException, InvocationTargetException {

    boolean changed = false;
    for (Annotation annotation : element.getDeclaredAnnotations()) {
        changed |= processAnnotation(annotation, prop, owner, access, appender);
    }// w w w  .ja v a2 s. co m
    return changed;
}

From source file:org.apache.bval.jsr.AnnotationProcessor.java

/**
 * Process JSR303 annotations./*from   w  ww  . j a va2s.  co m*/
 * 
 * @param prop
 *            potentially null
 * @param owner
 *            bean type
 * @param element
 *            whose annotations to read
 * @param access
 *            strategy for <code>prop</code>
 * @param appender
 *            handling accumulation
 * @return whether any processing took place
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 */
public boolean processAnnotations(Meta prop, Class<?> owner, AnnotatedElement element, AccessStrategy access,
        AppendValidation appender) throws IllegalAccessException, InvocationTargetException {

    boolean changed = false;
    for (final Annotation annotation : element.getDeclaredAnnotations()) {
        final Class<?> type = annotation.annotationType();
        if (type.getName().startsWith("java.lang.annotation.")) {
            continue;
        }
        changed = processAnnotation(annotation, prop, owner, access, appender, true) || changed;
    }
    return changed;
}

From source file:org.apache.openjpa.persistence.AnnotationPersistenceMetaDataParser.java

/**
 * Read annotations for the given member.
 *///from  w  ww.j  a v a 2  s.co m
private void parseMemberAnnotations(FieldMetaData fmd) {
    // look for persistence strategy in annotation table
    Member member = getRepository().getMetaDataFactory().getDefaults().getBackingMember(fmd);
    PersistenceStrategy pstrat = PersistenceMetaDataDefaults.getPersistenceStrategy(fmd, member);
    if (pstrat == null)
        return;
    fmd.setExplicit(true);

    AnnotatedElement el = (AnnotatedElement) member;
    boolean lob = (AccessController.doPrivileged(J2DoPrivHelper.isAnnotationPresentAction(el, Lob.class)))
            .booleanValue();
    if (isMetaDataMode()) {
        switch (pstrat) {
        case BASIC:
            parseBasic(fmd, (Basic) el.getAnnotation(Basic.class), lob);
            break;
        case MANY_ONE:
            parseManyToOne(fmd, (ManyToOne) el.getAnnotation(ManyToOne.class));
            break;
        case ONE_ONE:
            parseOneToOne(fmd, (OneToOne) el.getAnnotation(OneToOne.class));
            break;
        case EMBEDDED:
            parseEmbedded(fmd, (Embedded) el.getAnnotation(Embedded.class));
            break;
        case ONE_MANY:
            parseOneToMany(fmd, (OneToMany) el.getAnnotation(OneToMany.class));
            break;
        case MANY_MANY:
            parseManyToMany(fmd, (ManyToMany) el.getAnnotation(ManyToMany.class));
            break;
        case PERS:
            parsePersistent(fmd, (Persistent) el.getAnnotation(Persistent.class));
            break;
        case PERS_COLL:
            parsePersistentCollection(fmd, (PersistentCollection) el.getAnnotation(PersistentCollection.class));
            break;
        case ELEM_COLL:
            parseElementCollection(fmd, (ElementCollection) el.getAnnotation(ElementCollection.class));
            break;
        case PERS_MAP:
            parsePersistentMap(fmd, (PersistentMap) el.getAnnotation(PersistentMap.class));
            break;
        case TRANSIENT:
            break;
        default:
            throw new InternalException();
        }
    }

    if (isMappingOverrideMode() && lob)
        parseLobMapping(fmd);

    // extensions
    MetaDataTag tag;
    for (Annotation anno : el.getDeclaredAnnotations()) {
        tag = _tags.get(anno.annotationType());
        if (tag == null) {
            handleUnknownMemberAnnotation(fmd, anno);
            continue;
        }

        switch (tag) {
        case ACCESS:
            parseAccess(fmd, (Access) anno);
            break;
        case FLUSH_MODE:
            if (isMetaDataMode())
                warnFlushMode(fmd);
            break;
        case GENERATED_VALUE:
            if (isMappingOverrideMode())
                parseGeneratedValue(fmd, (GeneratedValue) anno);
            break;
        case ID:
        case EMBEDDED_ID:
            fmd.setPrimaryKey(true);
            break;
        case MAPPED_BY_ID:
            parseMapsId(fmd, (MapsId) anno);
            break;
        case MAP_KEY:
            if (isMappingOverrideMode())
                parseMapKey(fmd, (MapKey) anno);
            break;
        case MAP_KEY_CLASS:
            if (isMappingOverrideMode())
                parseMapKeyClass(fmd, (MapKeyClass) anno);
            break;
        case ORDER_BY:
            parseOrderBy(fmd, (OrderBy) el.getAnnotation(OrderBy.class));
            break;
        case SEQ_GENERATOR:
            if (isMappingOverrideMode())
                parseSequenceGenerator(el, (SequenceGenerator) anno);
            break;
        case VERSION:
            fmd.setVersion(true);
            break;
        case DEPENDENT:
            if (isMetaDataMode() && ((Dependent) anno).value())
                fmd.setCascadeDelete(ValueMetaData.CASCADE_AUTO);
            break;
        case ELEM_DEPENDENT:
            if (isMetaDataMode() && ((ElementDependent) anno).value())
                fmd.getElement().setCascadeDelete(ValueMetaData.CASCADE_AUTO);
            break;
        case ELEM_TYPE:
            if (isMetaDataMode())
                fmd.getElement().setTypeOverride(toOverrideType(((ElementType) anno).value()));
            break;
        case EXTERNAL_VALS:
            if (isMetaDataMode())
                fmd.setExternalValues(Strings.join(((ExternalValues) anno).value(), ","));
            break;
        case EXTERNALIZER:
            if (isMetaDataMode())
                fmd.setExternalizer(((Externalizer) anno).value());
            break;
        case FACTORY:
            if (isMetaDataMode())
                fmd.setFactory(((Factory) anno).value());
            break;
        case INVERSE_LOGICAL:
            if (isMetaDataMode())
                fmd.setInverse(((InverseLogical) anno).value());
            break;
        case KEY_DEPENDENT:
            if (isMetaDataMode() && ((KeyDependent) anno).value())
                fmd.getKey().setCascadeDelete(ValueMetaData.CASCADE_AUTO);
            break;
        case KEY_TYPE:
            if (isMetaDataMode())
                fmd.getKey().setTypeOverride(toOverrideType(((KeyType) anno).value()));
            break;
        case LOAD_FETCH_GROUP:
            if (isMetaDataMode())
                fmd.setLoadFetchGroup(((LoadFetchGroup) anno).value());
            break;
        case LRS:
            if (isMetaDataMode())
                fmd.setLRS(((LRS) anno).value());
            break;
        case READ_ONLY:
            if (isMetaDataMode())
                parseReadOnly(fmd, (ReadOnly) anno);
            break;
        case TYPE:
            if (isMetaDataMode())
                fmd.setTypeOverride(toOverrideType(((Type) anno).value()));
            break;
        default:
            throw new UnsupportedException(_loc.get("unsupported", fmd, anno.toString()));
        }
    }
}

From source file:org.apache.openjpa.persistence.jdbc.AnnotationPersistenceMappingParser.java

@Override
protected void parseMemberMappingAnnotations(FieldMetaData fmd) {
    FieldMapping fm = (FieldMapping) fmd;
    AnnotatedElement el = (AnnotatedElement) getRepository().getMetaDataFactory().getDefaults()
            .getBackingMember(fmd);// w  w  w  .java 2 s  . c  o m

    MappingTag tag;
    for (Annotation anno : el.getDeclaredAnnotations()) {
        tag = _tags.get(anno.annotationType());
        if (tag == null) {
            handleUnknownMemberMappingAnnotation(fm, anno);
            continue;
        }

        switch (tag) {
        case ASSOC_OVERRIDE:
            parseAssociationOverrides(fm, (AssociationOverride) anno);
            break;
        case ASSOC_OVERRIDES:
            parseAssociationOverrides(fm, ((AssociationOverrides) anno).value());
            break;
        case ATTR_OVERRIDE:
            parseAttributeOverrides(fm, (AttributeOverride) anno);
            break;
        case ATTR_OVERRIDES:
            parseAttributeOverrides(fm, ((AttributeOverrides) anno).value());
            break;
        case COL:
            parseColumns(fm, (javax.persistence.Column) anno);
            break;
        case COLS:
            parseColumns(fm, ((Columns) anno).value());
            break;
        case ENUMERATED:
            parseEnumerated(fm, (Enumerated) anno);
            break;
        case JOIN_COL:
            parseJoinColumns(fm, fm.getValueInfo(), true, (JoinColumn) anno);
            break;
        case JOIN_COLS:
            parseJoinColumns(fm, fm.getValueInfo(), true, ((JoinColumns) anno).value());
            break;
        case JOIN_TABLE:
            parseJoinTable(fm, (JoinTable) anno);
            break;
        case KEY_CLASS_CRIT:
            fm.getKeyMapping().getValueInfo().setUseClassCriteria(((KeyClassCriteria) anno).value());
            break;
        case KEY_COL:
            parseKeyColumns(fm, (KeyColumn) anno);
            break;
        case KEY_COLS:
            parseKeyColumns(fm, ((KeyColumns) anno).value());
            break;
        case KEY_EMBEDDED_MAPPING:
            KeyEmbeddedMapping kembed = (KeyEmbeddedMapping) anno;
            parseEmbeddedMapping(fm.getKeyMapping(),
                    DBIdentifier.newColumn(kembed.nullIndicatorColumnName(), delimit()),
                    DBIdentifier.newConstant(kembed.nullIndicatorAttributeName()), kembed.overrides());
            break;
        case KEY_FK:
            KeyForeignKey kfk = (KeyForeignKey) anno;
            parseForeignKey(fm.getKeyMapping().getValueInfo(), kfk.name(), kfk.enabled(), kfk.deferred(),
                    kfk.deleteAction(), kfk.updateAction());
            break;
        case KEY_INDEX:
            KeyIndex kidx = (KeyIndex) anno;
            parseIndex(fm.getKeyMapping().getValueInfo(), kidx.name(), kidx.enabled(), kidx.unique());
            break;
        case KEY_JOIN_COL:
            parseKeyJoinColumns(fm, (KeyJoinColumn) anno);
            break;
        case KEY_JOIN_COLS:
            parseKeyJoinColumns(fm, ((KeyJoinColumns) anno).value());
            break;
        case KEY_NONPOLY:
            fm.getKeyMapping().setPolymorphic(toPolymorphicConstant(((KeyNonpolymorphic) anno).value()));
            break;
        case KEY_STRAT:
            fm.getKeyMapping().getValueInfo().setStrategy(((KeyStrategy) anno).value());
            break;
        case MAP_KEY_COL:
            parseMapKeyColumn(fm, (MapKeyColumn) anno);
            break;
        case MAP_KEY_ENUMERATED:
            parseMapKeyEnumerated(fm, (MapKeyEnumerated) anno);
            break;
        case MAP_KEY_JOIN_COL:
            parseMapKeyJoinColumns(fm, (MapKeyJoinColumn) anno);
            break;
        case MAP_KEY_JOIN_COLS:
            parseMapKeyJoinColumns(fm, ((MapKeyJoinColumns) anno).value());
            break;
        case PK_JOIN_COL:
            parsePrimaryKeyJoinColumns(fm, (PrimaryKeyJoinColumn) anno);
            break;
        case PK_JOIN_COLS:
            parsePrimaryKeyJoinColumns(fm, ((PrimaryKeyJoinColumns) anno).value());
            break;
        case TABLE_GEN:
            parseTableGenerator(el, (TableGenerator) anno);
            break;
        case TEMPORAL:
            parseTemporal(fm, (Temporal) anno);
            break;
        case MAP_KEY_TEMPORAL:
            parseMapKeyTemporal(fm, (MapKeyTemporal) anno);
            break;
        case CLASS_CRIT:
            fm.getValueInfo().setUseClassCriteria(((ClassCriteria) anno).value());
            break;
        case CONTAINER_TABLE:
            parseContainerTable(fm, (ContainerTable) anno);
            break;
        case COLLECTION_TABLE:
            parseCollectionTable(fm, (CollectionTable) anno);
            break;
        case EAGER_FETCH_MODE:
            fm.setEagerFetchMode(toEagerFetchModeConstant(((EagerFetchMode) anno).value()));
            break;
        case ELEM_CLASS_CRIT:
            fm.getElementMapping().getValueInfo().setUseClassCriteria(((ElementClassCriteria) anno).value());
            break;
        case ELEM_COL:
            parseElementColumns(fm, (ElementColumn) anno);
            break;
        case ELEM_COLS:
            parseElementColumns(fm, ((ElementColumns) anno).value());
            break;
        case ELEM_EMBEDDED_MAPPING:
            ElementEmbeddedMapping ee = (ElementEmbeddedMapping) anno;
            parseEmbeddedMapping(fm.getElementMapping(),
                    DBIdentifier.newConstant(ee.nullIndicatorAttributeName()),
                    DBIdentifier.newColumn(ee.nullIndicatorColumnName(), delimit()), ee.overrides());
            break;
        case ELEM_FK:
            ElementForeignKey efk = (ElementForeignKey) anno;
            parseForeignKey(fm.getElementMapping().getValueInfo(), efk.name(), efk.enabled(), efk.deferred(),
                    efk.deleteAction(), efk.updateAction());
            break;
        case ELEM_INDEX:
            ElementIndex eidx = (ElementIndex) anno;
            parseIndex(fm.getElementMapping().getValueInfo(), eidx.name(), eidx.enabled(), eidx.unique());
            break;
        case ELEM_JOIN_COL:
            parseElementJoinColumns(fm, (ElementJoinColumn) anno);
            break;
        case ELEM_JOIN_COLS:
            parseElementJoinColumns(fm, ((ElementJoinColumns) anno).value());
            break;
        case ELEM_NONPOLY:
            fm.getElementMapping()
                    .setPolymorphic(toPolymorphicConstant(((ElementNonpolymorphic) anno).value()));
            break;
        case ELEM_STRAT:
            fm.getElementMapping().getValueInfo().setStrategy(((ElementStrategy) anno).value());
            break;
        case EMBEDDED_MAPPING:
            parseEmbeddedMapping(fm, (EmbeddedMapping) anno);
            break;
        case FK:
            parseForeignKey(fm.getValueInfo(), (ForeignKey) anno);
            break;
        case INDEX:
            parseIndex(fm.getValueInfo(), (Index) anno);
            break;
        case NONPOLY:
            fm.setPolymorphic(toPolymorphicConstant(((Nonpolymorphic) anno).value()));
            break;
        case ORDER_COLUMN:
            parseJavaxOrderColumn(fm, (javax.persistence.OrderColumn) anno);
            break;
        case ORDER_COL:
            parseOrderColumn(fm, (OrderColumn) anno);
            break;
        case STRAT:
            fm.getMappingInfo().setStrategy(((Strategy) anno).value());
            break;
        case UNIQUE:
            parseUnique(fm, (org.apache.openjpa.persistence.jdbc.Unique) anno);
            break;
        case X_EMBEDDED_MAPPING:
            XEmbeddedMapping embed = (XEmbeddedMapping) anno;
            parseEmbeddedMapping(fm, DBIdentifier.newColumn(embed.nullIndicatorColumnName(), delimit()),
                    DBIdentifier.newConstant(embed.nullIndicatorAttributeName()), embed.overrides());
            break;
        case X_JOIN_COL:
            parseXJoinColumns(fm, fm.getValueInfo(), true, (XJoinColumn) anno);
            break;
        case X_JOIN_COLS:
            parseXJoinColumns(fm, fm.getValueInfo(), true, ((XJoinColumns) anno).value());
            break;
        default:
            throw new UnsupportedException(_loc.get("unsupported", fm, anno.toString()));
        }
    }
}

From source file:org.apache.openjpa.persistence.PersistenceMetaDataDefaults.java

/**
 * Return the code for the strategy of the given member. Return null if
 * no strategy./* w  w  w. j  ava 2s. c o  m*/
 */
public static PersistenceStrategy getPersistenceStrategy(FieldMetaData fmd, Member member,
        boolean ignoreTransient) {
    if (member == null)
        return null;
    AnnotatedElement el = (AnnotatedElement) member;
    if (!ignoreTransient
            && (AccessController.doPrivileged(J2DoPrivHelper.isAnnotationPresentAction(el, Transient.class)))
                    .booleanValue())
        return TRANSIENT;
    if (fmd != null && fmd.getManagement() != FieldMetaData.MANAGE_PERSISTENT)
        return null;

    // look for persistence strategy in annotation table
    PersistenceStrategy pstrat = null;
    for (Annotation anno : el.getDeclaredAnnotations()) {
        if (pstrat != null && _strats.containsKey(anno.annotationType()))
            throw new MetaDataException(_loc.get("already-pers", member));
        if (pstrat == null)
            pstrat = _strats.get(anno.annotationType());
    }
    if (pstrat != null)
        return pstrat;

    Class type;
    int code;
    if (fmd != null) {
        type = fmd.getType();
        code = fmd.getTypeCode();
    } else if (member instanceof Field) {
        type = ((Field) member).getType();
        code = JavaTypes.getTypeCode(type);
    } else {
        type = ((Method) member).getReturnType();
        code = JavaTypes.getTypeCode(type);
    }

    switch (code) {
    case JavaTypes.ARRAY:
        if (type == byte[].class || type == char[].class || type == Byte[].class || type == Character[].class)
            return BASIC;
        break;
    case JavaTypes.BOOLEAN:
    case JavaTypes.BOOLEAN_OBJ:
    case JavaTypes.BYTE:
    case JavaTypes.BYTE_OBJ:
    case JavaTypes.CHAR:
    case JavaTypes.CHAR_OBJ:
    case JavaTypes.DOUBLE:
    case JavaTypes.DOUBLE_OBJ:
    case JavaTypes.FLOAT:
    case JavaTypes.FLOAT_OBJ:
    case JavaTypes.INT:
    case JavaTypes.INT_OBJ:
    case JavaTypes.LONG:
    case JavaTypes.LONG_OBJ:
    case JavaTypes.SHORT:
    case JavaTypes.SHORT_OBJ:
    case JavaTypes.STRING:
    case JavaTypes.BIGDECIMAL:
    case JavaTypes.BIGINTEGER:
    case JavaTypes.DATE:
        return BASIC;
    case JavaTypes.OBJECT:
        if (Enum.class.isAssignableFrom(type))
            return BASIC;
        break;
    }

    //### EJB3: what if defined in XML?
    if ((AccessController.doPrivileged(J2DoPrivHelper.isAnnotationPresentAction(type, Embeddable.class)))
            .booleanValue())
        return EMBEDDED;
    if (Serializable.class.isAssignableFrom(type))
        return BASIC;
    return null;
}

From source file:org.omnaest.utils.reflection.ReflectionUtils.java

/**
 * Returns all {@link AnnotatedElement#getDeclaredAnnotations()} as {@link Set}
 * //w w  w.  ja  v a  2  s . c  o  m
 * @param annotatedElement
 *          {@link Field}
 * @return
 */
public static Set<Annotation> declaredAnnotationSet(AnnotatedElement annotatedElement) {
    return annotatedElement != null ? SetUtils.valueOf(annotatedElement.getDeclaredAnnotations())
            : new LinkedHashSet<Annotation>();
}

From source file:org.springframework.core.annotation.AnnotationUtils.java

/**
 * Perform the search algorithm for {@link #findAnnotation(AnnotatedElement, Class)}
 * avoiding endless recursion by tracking which annotations have already
 * been <em>visited</em>./*from  w  w  w  . j  a va2 s . co m*/
 * @param annotatedElement the {@code AnnotatedElement} on which to find the annotation
 * @param annotationType the annotation type to look for, both locally and as a meta-annotation
 * @param visited the set of annotations that have already been visited
 * @return the first matching annotation, or {@code null} if not found
 * @since 4.2
 */
@Nullable
private static <A extends Annotation> A findAnnotation(AnnotatedElement annotatedElement,
        Class<A> annotationType, Set<Annotation> visited) {
    try {
        A annotation = annotatedElement.getDeclaredAnnotation(annotationType);
        if (annotation != null) {
            return annotation;
        }
        for (Annotation declaredAnn : annotatedElement.getDeclaredAnnotations()) {
            Class<? extends Annotation> declaredType = declaredAnn.annotationType();
            if (!isInJavaLangAnnotationPackage(declaredType) && visited.add(declaredAnn)) {
                annotation = findAnnotation((AnnotatedElement) declaredType, annotationType, visited);
                if (annotation != null) {
                    return annotation;
                }
            }
        }
    } catch (Throwable ex) {
        handleIntrospectionFailure(annotatedElement, ex);
    }
    return null;
}