Example usage for java.lang.reflect AnnotatedElement getAnnotation

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

Introduction

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

Prototype

<T extends Annotation> T getAnnotation(Class<T> annotationClass);

Source Link

Document

Returns this element's annotation for the specified type if such an annotation is present, else null.

Usage

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

/**
 * Read annotations for the given member.
 *//*from w  w  w .  jav  a2  s . com*/
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.AnnotationPersistenceXMLMetaDataParser.java

private void populateFromReflection(Class cls, XMLMetaData meta) {
    Member[] members;/*from   w ww  .j  av a  2  s .  c om*/

    Class superclass = cls.getSuperclass();

    // handle inheritance at sub-element level
    if ((AccessController.doPrivileged(J2DoPrivHelper.isAnnotationPresentAction(superclass, xmlTypeClass)))
            .booleanValue())
        populateFromReflection(superclass, meta);

    try {
        if (StringUtils.equals(
                xmlAccessorValue.invoke(cls.getAnnotation(xmlAccessorTypeClass), new Object[] {}).toString(),
                "FIELD"))
            members = cls.getDeclaredFields();
        else
            members = cls.getDeclaredMethods();

        for (int i = 0; i < members.length; i++) {
            Member member = members[i];
            AnnotatedElement el = (AnnotatedElement) member;
            XMLMetaData field = null;
            if (el.getAnnotation(xmlElementClass) != null) {
                String xmlname = (String) xmlElementName.invoke(el.getAnnotation(xmlElementClass),
                        new Object[] {});
                // avoid JAXB XML bind default name
                if (StringUtils.equals(XMLMetaData.defaultName, xmlname))
                    xmlname = member.getName();
                if ((AccessController.doPrivileged(
                        J2DoPrivHelper.isAnnotationPresentAction(((Field) member).getType(), xmlTypeClass)))
                                .booleanValue()) {
                    field = _repos.addXMLClassMetaData(((Field) member).getType());
                    parseXmlRootElement(((Field) member).getType(), field);
                    populateFromReflection(((Field) member).getType(), field);
                    field.setXmltype(XMLMetaData.XMLTYPE);
                    field.setXmlname(xmlname);
                } else {
                    field = _repos.newXMLFieldMetaData(((Field) member).getType(), member.getName());
                    field.setXmltype(XMLMetaData.ELEMENT);
                    field.setXmlname(xmlname);
                    field.setXmlnamespace((String) xmlElementNamespace.invoke(el.getAnnotation(xmlElementClass),
                            new Object[] {}));
                }
            } else if (el.getAnnotation(xmlAttributeClass) != null) {
                field = _repos.newXMLFieldMetaData(((Field) member).getType(), member.getName());
                field.setXmltype(XMLFieldMetaData.ATTRIBUTE);
                String xmlname = (String) xmlAttributeName.invoke(el.getAnnotation(xmlAttributeClass),
                        new Object[] {});
                // avoid JAXB XML bind default name
                if (StringUtils.equals(XMLMetaData.defaultName, xmlname))
                    xmlname = member.getName();
                field.setXmlname("@" + xmlname);
                field.setXmlnamespace((String) xmlAttributeNamespace.invoke(el.getAnnotation(xmlAttributeClass),
                        new Object[] {}));
            }
            if (field != null)
                meta.addField(member.getName(), field);
        }
    } catch (Exception e) {
    }
}

From source file:org.apache.sling.models.impl.injectors.ChildResourceInjector.java

@Override
public InjectAnnotationProcessor2 createAnnotationProcessor(Object adaptable, AnnotatedElement element) {
    // check if the element has the expected annotation
    ChildResource annotation = element.getAnnotation(ChildResource.class);
    if (annotation != null) {
        return new ChildResourceAnnotationProcessor(annotation, adaptable);
    }//w ww.  jav  a 2s .  c o m
    return null;
}

From source file:org.apache.sling.models.impl.injectors.OSGiServiceInjector.java

public Object getValue(@Nonnull Object adaptable, String name, @Nonnull Type type,
        @Nonnull AnnotatedElement element, @Nonnull DisposalCallbackRegistry callbackRegistry) {
    OSGiService annotation = element.getAnnotation(OSGiService.class);
    String filterString = null;//from   w ww .j av a  2 s . c o m
    if (annotation != null) {
        if (StringUtils.isNotBlank(annotation.filter())) {
            filterString = annotation.filter();
        }
    } else {
        Filter filter = element.getAnnotation(Filter.class);
        if (filter != null) {
            filterString = filter.value();
        }
    }
    return getValue(adaptable, type, filterString, callbackRegistry);
}

From source file:org.apache.sling.models.impl.injectors.OSGiServiceInjector.java

@Override
public InjectAnnotationProcessor2 createAnnotationProcessor(AnnotatedElement element) {
    // check if the element has the expected annotation
    OSGiService annotation = element.getAnnotation(OSGiService.class);
    if (annotation != null) {
        return new OSGiServiceAnnotationProcessor(annotation);
    }//ww w  .ja va 2s  .  co m
    return null;
}

From source file:org.apache.sling.models.impl.injectors.ResourcePathInjector.java

@Override
public Object getValue(@Nonnull Object adaptable, String name, @Nonnull Type declaredType,
        @Nonnull AnnotatedElement element, @Nonnull DisposalCallbackRegistry callbackRegistry) {
    String[] resourcePaths = null;
    Path pathAnnotation = element.getAnnotation(Path.class);
    ResourcePath resourcePathAnnotation = element.getAnnotation(ResourcePath.class);
    if (pathAnnotation != null) {
        resourcePaths = getPathsFromAnnotation(pathAnnotation);
    } else if (resourcePathAnnotation != null) {
        resourcePaths = getPathsFromAnnotation(resourcePathAnnotation);
    }/*from   ww  w.j  a va2s.c o  m*/
    if (ArrayUtils.isEmpty(resourcePaths) && name != null) {
        // try the valuemap
        ValueMap map = getValueMap(adaptable);
        if (map != null) {
            resourcePaths = map.get(name, String[].class);
        }
    }
    if (ArrayUtils.isEmpty(resourcePaths)) {
        // could not find a path to inject
        return null;
    }

    ResourceResolver resolver = getResourceResolver(adaptable);
    if (resolver == null) {
        return null;
    }
    List<Resource> resources = getResources(resolver, resourcePaths, name);

    if (resources == null || resources.isEmpty()) {
        return null;
    }
    // unwrap if necessary
    if (isDeclaredTypeCollection(declaredType)) {
        return resources;
    } else if (resources.size() == 1) {
        return resources.get(0);
    } else {
        // multiple resources to inject, but field is not a list
        LOG.warn("Cannot inject multiple resources into field {} since it is not declared as a list", name);
        return null;
    }

}

From source file:org.apache.sling.models.impl.injectors.ResourcePathInjector.java

@Override
public InjectAnnotationProcessor2 createAnnotationProcessor(AnnotatedElement element) {
    // check if the element has the expected annotation
    ResourcePath annotation = element.getAnnotation(ResourcePath.class);
    if (annotation != null) {
        return new ResourcePathAnnotationProcessor(annotation);
    }//from   ww w .ja  v  a2  s .  c  om
    return null;
}

From source file:org.apache.sling.models.impl.injectors.ValueMapInjector.java

@Override
public InjectAnnotationProcessor createAnnotationProcessor(Object adaptable, AnnotatedElement element) {
    // check if the element has the expected annotation
    ValueMapValue annotation = element.getAnnotation(ValueMapValue.class);
    if (annotation != null) {
        return new ValueAnnotationProcessor(annotation, adaptable);
    }//from ww w  . j a va  2 s . c  o m
    return null;
}

From source file:org.apache.sling.models.impl.model.AbstractInjectableElement.java

private static String getName(AnnotatedElement element, String defaultName,
        InjectAnnotationProcessor2 annotationProcessor) {
    String name = null;//www .j  a v  a2 s  . c o m
    if (annotationProcessor != null) {
        name = annotationProcessor.getName();
    }
    if (name == null) {
        Named namedAnnotation = element.getAnnotation(Named.class);
        if (namedAnnotation != null) {
            name = namedAnnotation.value();
        } else {
            name = defaultName;
        }
    }
    return name;
}

From source file:org.apache.sling.models.impl.model.AbstractInjectableElement.java

private static String getVia(AnnotatedElement element, InjectAnnotationProcessor2 annotationProcessor) {
    String via = null;/*from  w w  w .  j a  v a  2 s . c  o  m*/
    if (annotationProcessor != null) {
        via = annotationProcessor.getVia();
    }
    if (via == null) {
        Via viaAnnotation = element.getAnnotation(Via.class);
        if (viaAnnotation != null) {
            via = viaAnnotation.value();
        }
    }
    return via;
}