Java Code Examples for javax.lang.model.element.AnnotationMirror#getAnnotationType()

The following examples show how to use javax.lang.model.element.AnnotationMirror#getAnnotationType() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AnnotationObjectProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
static void findQualifiers(Element element , 
        AnnotationModelHelper helper , boolean event , 
        AnnotationHandleStrategy strategy )
{
    List<? extends AnnotationMirror> allAnnotationMirrors = 
        helper.getCompilationController().getElements().
        getAllAnnotationMirrors( element );
    for (AnnotationMirror annotationMirror : allAnnotationMirrors) {
        DeclaredType annotationType = annotationMirror
                .getAnnotationType();
        if ( annotationType == null || annotationType.getKind() == TypeKind.ERROR){
            continue;
        }
        TypeElement annotationElement = (TypeElement) annotationType
                .asElement();
        if (annotationElement!= null && isQualifier(annotationElement, 
                helper , event )) 
        {
            strategy.handleAnnotation(annotationMirror , annotationElement );
        }
    }
}
 
Example 2
Source File: CompletionCandidatesMetaData.java    From picocli with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the completion candidates from the annotations present on the specified element.
 * @param element the method or field annotated with {@code @Option} or {@code @Parameters}
 * @return the completion candidates or {@code null} if not found
 */
public static Iterable<String> extract(Element element) {
    List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors();
    for (AnnotationMirror mirror : annotationMirrors) {
        DeclaredType annotationType = mirror.getAnnotationType();
        if (TypeUtil.isOption(annotationType) || TypeUtil.isParameter(annotationType)) {
            Map<? extends ExecutableElement, ? extends AnnotationValue> elementValues = mirror.getElementValues();
            for (ExecutableElement attribute : elementValues.keySet()) {
                if ("completionCandidates".equals(attribute.getSimpleName().toString())) {
                    AnnotationValue typeMirror = elementValues.get(attribute);
                    return new CompletionCandidatesMetaData((TypeMirror) typeMirror);
                }
            }
        }
    }
    return null;
}
 
Example 3
Source File: TypeConverterMetaData.java    From picocli with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the type converters from the annotations present on the specified element.
 * @param element the method or field annotated with {@code @Option} or {@code @Parameters}
 * @return the type converters or an empty array if not found
 */
@SuppressWarnings("unchecked")
public static TypeConverterMetaData[] extract(Element element) {
    List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors();
    for (AnnotationMirror mirror : annotationMirrors) {
        DeclaredType annotationType = mirror.getAnnotationType();
        if (TypeUtil.isOption(annotationType) || TypeUtil.isParameter(annotationType)) {
            Map<? extends ExecutableElement, ? extends AnnotationValue> elementValues = mirror.getElementValues();
            for (ExecutableElement attribute : elementValues.keySet()) {
                if ("converter".equals(attribute.getSimpleName().toString())) {
                    AnnotationValue list = elementValues.get(attribute);
                    List<AnnotationValue> typeMirrors = (List<AnnotationValue>) list.getValue();
                    List<TypeConverterMetaData> result = new ArrayList<TypeConverterMetaData>();
                    for (AnnotationValue annotationValue : typeMirrors) {
                        result.add(new TypeConverterMetaData((TypeMirror) annotationValue.getValue()));
                    }
                    return result.toArray(new TypeConverterMetaData[0]);
                }
            }
        }
    }
    return new TypeConverterMetaData[0];
}
 
Example 4
Source File: MultiModuleSuperFieldDelegate.java    From data-mediator with Apache License 2.0 6 votes vote down vote up
@Override
public Set<FieldData> getDependFields(TypeElement te) {
    Set<FieldData> list = new HashSet<>();

    List<? extends AnnotationMirror> mirrors = te.getAnnotationMirrors();
    AnnotationMirror expect = null;
    for(AnnotationMirror am : mirrors){
        DeclaredType type = am.getAnnotationType();
        if(type.toString().equals(Fields.class.getName())){
            expect = am;
            break;
        }
    }
    if(expect != null){
        ElementHelper.parseFields(elements, types, expect, list, pp);
    }
    //a depend b, b depend c ,,, etc.
    List<? extends TypeMirror> superInterfaces = te.getInterfaces();
    for(TypeMirror tm : superInterfaces){
        final TypeElement newTe = (TypeElement) ((DeclaredType) tm).asElement();
        list.addAll(getDependFields(newTe)); //recursion
    }
    return list;
}
 
Example 5
Source File: EventInjectionPointLogic.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private Triple<VariableElement, Integer, Void> doGetObserverParameter( 
        ExecutableElement element )
{
    List<? extends VariableElement> parameters = element.getParameters();
    int index = 0 ; 
    for (VariableElement parameter : parameters) {
        List<? extends AnnotationMirror> allAnnotationMirrors = 
            getCompilationController().getElements().
            getAllAnnotationMirrors( parameter );
        for (AnnotationMirror annotationMirror : allAnnotationMirrors) {
            DeclaredType annotationType = annotationMirror.getAnnotationType();
            TypeElement annotation = (TypeElement)annotationType.asElement();
            if ( annotation == null ){
                continue;
            }
            if ( OBSERVES_ANNOTATION.contentEquals( annotation.getQualifiedName())){
                return new Triple<VariableElement, Integer, Void>(parameter, index, null);
            }
        }
        index++;
    }
    return null;
}
 
Example 6
Source File: UseDatabaseGeneratorTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static void checkDatasourceField(TypeElement typeElement, String name) {
    List<VariableElement> elements = ElementFilter.fieldsIn(typeElement.getEnclosedElements());
    VariableElement variableElement = elements.get(0);
    assertTrue(variableElement.getSimpleName().contentEquals(name)); // field name
    DeclaredType declaredType = (DeclaredType) variableElement.asType();
    TypeElement returnTypeElement = (TypeElement) declaredType.asElement();
    assertTrue(returnTypeElement.getQualifiedName().contentEquals("javax.sql.DataSource")); // field type
    AnnotationMirror annotationMirror = variableElement.getAnnotationMirrors().get(0);
    DeclaredType annotationDeclaredType = annotationMirror.getAnnotationType();
    TypeElement annotationTypeElement = (TypeElement) annotationDeclaredType.asElement();
    assertTrue(annotationTypeElement.getQualifiedName().contentEquals("javax.annotation.Resource")); // annotation type
    Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry = annotationMirror.getElementValues().entrySet().iterator().next();
    String attributeName = entry.getKey().getSimpleName().toString();
    String attributeValue = (String) entry.getValue().getValue();
    assertEquals("name", attributeName); // attributes
    assertEquals(name, attributeValue);
}
 
Example 7
Source File: BindingsPanel.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected void appendAnnotationMirror( AnnotationMirror mirror , StringBuilder builder , 
        boolean isFqn )
{
    DeclaredType type = mirror.getAnnotationType();
    Element annotation = type.asElement();
    
    builder.append('@');
    String annotationName ;
    if ( isFqn ) {
        annotationName= ( annotation instanceof TypeElement )?
            ((TypeElement)annotation).getQualifiedName().toString() : 
                annotation.getSimpleName().toString();
    }
    else { 
        annotationName = annotation.getSimpleName().toString();
    }
    
    builder.append( annotationName );
    
    appendBindingParamters( mirror , builder );
    
    builder.append(", ");           // NOI18N
}
 
Example 8
Source File: WebBeansModelProviderImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public String getName( Element element)
{
    String name = inspectSpecializes( element );
    if ( name != null ){
        return name;
    }
    List<AnnotationMirror> allStereotypes = getAllStereotypes(element, 
            getModel().getHelper().getHelper());
    for (AnnotationMirror annotationMirror : allStereotypes) {
        DeclaredType annotationType = annotationMirror.getAnnotationType();
        TypeElement annotation = (TypeElement)annotationType.asElement();
        if ( AnnotationObjectProvider.hasAnnotation(annotation, 
                NAMED_QUALIFIER_ANNOTATION, getModel().getHelper() ) )
        {
            return getNamedName(element , null);
        }
    }
    return null;
}
 
Example 9
Source File: WebBeansActionHelper.java    From netbeans with Apache License 2.0 6 votes vote down vote up
static boolean hasAnnotation(Element element,String fqn){
    List<? extends AnnotationMirror> annotationMirrors = 
        element.getAnnotationMirrors();
    for (AnnotationMirror annotationMirror : annotationMirrors) {
        DeclaredType annotationType = annotationMirror.getAnnotationType();
        Element annotationElement = annotationType.asElement();
        if ( annotationElement instanceof TypeElement ){
            Name qualifiedName = ((TypeElement)annotationElement).
                getQualifiedName();
            if ( qualifiedName.contentEquals(fqn)){
                return true;
            }
        }
    }
    return false;
}
 
Example 10
Source File: VerifierAnnotationProcessor.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static AnnotationMirror findAnnotationMirror(ProcessingEnvironment processingEnv, List<? extends AnnotationMirror> mirrors, Class<?> annotationClass) {
    TypeElement expectedAnnotationType = processingEnv.getElementUtils().getTypeElement(annotationClass.getCanonicalName());
    for (AnnotationMirror mirror : mirrors) {
        DeclaredType annotationType = mirror.getAnnotationType();
        TypeElement actualAnnotationType = (TypeElement) annotationType.asElement();
        if (actualAnnotationType.equals(expectedAnnotationType)) {
            return mirror;
        }
    }
    return null;
}
 
Example 11
Source File: AnnotationScanner.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void handleAnnotation(final AnnotationHandler handler, 
        final TypeElement typeElement, final Element element, 
        final String searchedTypeName, Set<ElementKind> kinds, 
        boolean includeDerived) throws InterruptedException 
{
    
    List<? extends AnnotationMirror> fieldAnnotationMirrors = element.getAnnotationMirrors();
    for (AnnotationMirror annotationMirror : fieldAnnotationMirrors) {
        DeclaredType annotationType = annotationMirror.getAnnotationType();
        String annotationTypeName = getHelper().getAnnotationTypeName(annotationType);
        // issue 110819: need to compare the real type names, since the annotation can be @<any>
        if (searchedTypeName.equals(annotationTypeName)) {
            LOGGER.log(
                    Level.FINE,
                    "notifying type {0}, element {1}, annotation {2}", // NOI18N
                    new Object[] { typeElement.getQualifiedName(), 
                            element.getSimpleName(), annotationMirror });
            // this check was originally missed for Types........
            if ( kinds.contains( element.getKind())){
                handler.handleAnnotation(typeElement, element, annotationMirror);
            }
            if ( includeDerived && element.getKind() == ElementKind.CLASS ){
                discoverHierarchy( typeElement , annotationMirror , 
                        handler, kinds);
            }
        } else {
            LOGGER.log(
                    Level.FINE,
                    "type name mismatch, ignoring type {0}, element {1}, annotation {2}", // NOI18N
                    new Object[] { typeElement.getQualifiedName(), element.getSimpleName(), annotationMirror });
        }
    }
}
 
Example 12
Source File: ModelUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Collection<String> extractAnnotationNames(Element elem) {
    Collection<String> annotationsOnElement = new LinkedList<String>();

    for (AnnotationMirror ann : elem.getAnnotationMirrors()) {
        TypeMirror annType = ann.getAnnotationType();
        Element typeElem = ((DeclaredType) annType).asElement();
        String typeName = ((TypeElement) typeElem).getQualifiedName().toString();
        annotationsOnElement.add(typeName);
    }

    return annotationsOnElement;
}
 
Example 13
Source File: SourceModeler.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Collection<Method> doBuildResource( final Resource resource,
        TypeElement clazz, CompilationController controller , 
        Collection<TypeMirror> boxedPrimitives )
{
    String fqn = clazz.getQualifiedName().toString();
    if ( resourceFqns.contains( fqn)){
        return Collections.emptyList();
    }
    else {
        resourceFqns.add( fqn);
    }
    Collection<Method> result = new LinkedList<Method>();

    List<ExecutableElement> methods = ElementFilter.methodsIn(controller
            .getElements().getAllMembers(clazz));

    for (ExecutableElement method : methods) {
        List<? extends AnnotationMirror> annotationMirrors = controller
                .getElements().getAllAnnotationMirrors(method);
        Map<String, AnnotationMirror> restAnnotations = new HashMap<String, 
            AnnotationMirror>();
        for (AnnotationMirror annotationMirror : annotationMirrors) {
            DeclaredType annotationType = annotationMirror
                    .getAnnotationType();
            Element annotationElement = annotationType.asElement();
            if (annotationElement instanceof TypeElement) {
                TypeElement annotation = (TypeElement) annotationElement;
                String fqnAnnotation = annotation.getQualifiedName()
                        .toString();
                if (isRestAnnotation(fqnAnnotation)) {
                    restAnnotations.put(fqnAnnotation, annotationMirror);
                }
            }
        }
        Collection<Method> collection = createRestMethods(resource,
                restAnnotations, clazz, method, controller, boxedPrimitives);
        result.addAll(collection);
    }
    return result;
}
 
Example 14
Source File: WebBeansModelProviderImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String doGetName( Element original , Element element ){
    List<? extends AnnotationMirror> annotations = getModel().getHelper().
        getCompilationController().getElements().getAllAnnotationMirrors( 
            element);
    for (AnnotationMirror annotationMirror : annotations) {
    DeclaredType type = annotationMirror.getAnnotationType();
    TypeElement annotationElement = (TypeElement)type.asElement();
        if ( NAMED_QUALIFIER_ANNOTATION.contentEquals( 
                annotationElement.getQualifiedName()))
        {
            return getNamedName( original , annotationMirror );
        }
    }
    return null;
}
 
Example 15
Source File: DefaultBindingTypeFilter.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
void filter( Set<T> set ) {
    super.filter(set);
    for (Iterator<T> iterator = set.iterator(); iterator
            .hasNext();)
    {
        Element element = iterator.next();
        List<? extends AnnotationMirror> allAnnotationMirrors = getImplementation()
                .getHelper().getCompilationController().getElements()
                .getAllAnnotationMirrors(element);
        Set<String> qualifierNames = new HashSet<String>();
        for (AnnotationMirror annotationMirror : allAnnotationMirrors) {
            DeclaredType annotationType = annotationMirror
                    .getAnnotationType();
            TypeElement annotationElement = (TypeElement) annotationType
                    .asElement();
            if ( annotationElement == null ){
                continue;
            }
            String annotationName = annotationElement.getQualifiedName()
                .toString();
            if ( WebBeansModelProviderImpl.ANY_QUALIFIER_ANNOTATION.equals(
                    annotationName) || 
                    WebBeansModelProviderImpl.NAMED_QUALIFIER_ANNOTATION.equals(
                            annotationName))
            {
                continue;
            }
            if (isQualifier(annotationElement)) {
                qualifierNames.add(annotationName);
            }
        }
        if ( qualifierNames.contains(
                WebBeansModelProviderImpl.DEFAULT_QUALIFIER_ANNOTATION))
        {
            continue;
        }
        if ( (element instanceof TypeElement) && (
            AnnotationObjectProvider.checkSuper((TypeElement)element, 
                    WebBeansModelProviderImpl.DEFAULT_QUALIFIER_ANNOTATION, 
                    getImplementation().getHelper())!=null ))
        {
                continue;
        }
        else if ( element instanceof ExecutableElement ){
            Element specialized = 
                MemberCheckerFilter.getSpecialized( (ExecutableElement)element, 
                        getImplementation(), 
                        WebBeansModelProviderImpl.DEFAULT_QUALIFIER_ANNOTATION);
            if ( specialized!= null){
                continue;
            }
        }
        if (qualifierNames.size() != 0) {
            iterator.remove();
        }
    }
}
 
Example 16
Source File: JavaEnvironment.java    From j2cl with Apache License 2.0 4 votes vote down vote up
private static boolean isNonNullAnnotation(AnnotationMirror annotation) {
  Type annotationType = (Type) annotation.getAnnotationType();
  return JsInteropAnnotationUtils.isJsNonNullAnnotation(annotationType)
      || Ascii.equalsIgnoreCase(annotationType.asElement().getSimpleName().toString(), "Nonnull");
}
 
Example 17
Source File: FieldInjectionPointLogic.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private Set<Element> getProductions( 
        List<AnnotationMirror> qualifierAnnotations, AtomicBoolean cancel) 
{
    List<Set<Element>> bindingCollections = 
        new ArrayList<Set<Element>>( qualifierAnnotations.size());
    /*
     * One need to handle special case with @Default annotation 
     * in case of specialization. There can be a case 
     * when production method doesn't explicitly declare @Default but 
     * specialize other method with several appropriate qualifiers.
     * In this case original method will have @Default along with 
     * qualifiers "inherited" from specialized methods.  
     */
    boolean hasDefault = getModel().getHelper().getAnnotationsByType( 
            qualifierAnnotations ).get(DEFAULT_QUALIFIER_ANNOTATION) != null ;
    Set<Element> currentBindings = new HashSet<Element>();
    for (AnnotationMirror annotationMirror : qualifierAnnotations) {
        if(cancel.get()) {
            currentBindings.clear();
            break;
        }
        DeclaredType type = annotationMirror.getAnnotationType();
        TypeElement annotationElement = (TypeElement)type.asElement();
        if ( annotationElement == null ){
            continue;
        }
        String annotationFQN = annotationElement.getQualifiedName().toString();
        findAnnotation( bindingCollections, annotationFQN , hasDefault,
                currentBindings, cancel);
    }

    if ( hasDefault ){
        bindingCollections.add( currentBindings );
    }
    
    Set<Element> result= null;
    for ( int i=0; i<bindingCollections.size() ; i++ ){
        Set<Element> list = bindingCollections.get(i);
        if ( i==0 ){
            result = list;
        }
        else {
            result.retainAll( list );
        }
    }
    if ( result == null ){
        return Collections.emptySet();
    }
    return result;
}
 
Example 18
Source File: SourceModeler.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private RestEntity getParamEntity( CompilationController controller,
        Collection<TypeMirror> boxedPrimitives, 
        ExecutableElement methodElement, ExecutableType method )

{
    List<? extends VariableElement> parameters = methodElement.getParameters();
    int index=-1;
    int i=0;
    for (VariableElement variableElement : parameters) {
        List<? extends AnnotationMirror> annotationMirrors = 
            variableElement.getAnnotationMirrors();
        boolean isUriParam = false;
        for (AnnotationMirror annotationMirror : annotationMirrors) {
            DeclaredType annotationType = annotationMirror.getAnnotationType();
            Element annotationElement = annotationType.asElement();
            if ( annotationElement instanceof TypeElement ){
                String fqn = ((TypeElement)annotationElement).
                    getQualifiedName().toString();
                // skip arguments which are URI parameters ( query param or path param )
                if ( fqn.equals(RestConstants.QUERY_PARAM) || 
                        fqn.equals(RestConstants.PATH_PARAM))
                {
                    isUriParam = true;
                    break;
                }
            }
        }
        if ( !isUriParam ){
            index = i;
            break;
        }
        i++;
    }
    
    if ( index==-1 ){
        return new RestEntity(true);
    }
    List<? extends TypeMirror> parameterTypes = method.getParameterTypes();
    TypeMirror typeMirror = parameterTypes.get( index );
    return getRestEntity(controller, boxedPrimitives, typeMirror);
}
 
Example 19
Source File: FieldInjectionPointLogic.java    From netbeans with Apache License 2.0 4 votes vote down vote up
protected boolean hasAnyQualifier( VariableElement element,boolean injectRequired,
        boolean eventQualifiers, List<AnnotationMirror> quilifierAnnotations ) 
        throws InjectionPointDefinitionError
{
    List<? extends AnnotationMirror> annotations = 
        getModel().getHelper().getCompilationController().getElements().
        getAllAnnotationMirrors(element);
    boolean isProducer = false;
    
    /* Single @Any annotation means skip searching in qualifiers .
     * One need to check any bean that has required type .
     * @Any qualifier type along with other qualifiers 
     * equivalent to the same list of qualifiers without @Any.
     */
    boolean anyQualifier = false;
    
    boolean hasInject = false;
    
    for (AnnotationMirror annotationMirror : annotations) {
        DeclaredType type = annotationMirror.getAnnotationType();
        TypeElement annotationElement = (TypeElement)type.asElement();
        if ( annotationElement == null ){
            continue;
        }
        if ( ANY_QUALIFIER_ANNOTATION.equals( 
                annotationElement.getQualifiedName().toString()))
        {
            anyQualifier = true;
        }
        else if ( isQualifier( annotationElement , getModel().getHelper(),
                eventQualifiers) )
        {
            quilifierAnnotations.add( annotationMirror );
        }
        if ( PRODUCER_ANNOTATION.contentEquals( 
                annotationElement.getQualifiedName()))
        {
            isProducer = true;
        }
        else if ( INJECT_ANNOTATION.contentEquals( 
                annotationElement.getQualifiedName()))
        {
            hasInject = true;
        }
    }
    if ( isProducer ){
        throw new InjectionPointDefinitionError(
                NbBundle.getMessage( WebBeansModelProviderImpl.class, 
                        "ERR_ProducerInjectPoint" ,     // NOI18N
                        element.getSimpleName() ));
    }
    if ( element.asType().getKind() == TypeKind.TYPEVAR ){
        throw new InjectionPointDefinitionError(
                NbBundle.getMessage( WebBeansModelProviderImpl.class, 
                        "ERR_InjectPointTypeVar" ,           // NOI18N
                        element.getSimpleName() ));
    }
    if ( injectRequired ){
        checkInjectionPoint(element);
    }
    if ( injectRequired && !hasInject ){
        throw new InjectionPointDefinitionError(
                NbBundle.getMessage( WebBeansModelProviderImpl.class, 
                        "ERR_NoInjectPoint" ,           // NOI18N
                        element.getSimpleName() ));
    }
    return anyQualifier;
}
 
Example 20
Source File: ParameterInjectionPointLogic.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static String getDeclaredScope( AnnotationModelHelper helper,
        List<? extends AnnotationMirror> annotationMirrors,
        ScopeChecker scopeChecker , NormalScopeChecker normalScopeChecker ,
        boolean singleScopeRequired ) throws CdiException
{
    List<? extends AnnotationMirror> annotations = annotationMirrors;
    if ( !singleScopeRequired ){
        annotations = new ArrayList<AnnotationMirror>( 
                annotationMirrors);
        Collections.reverse( annotations );
    }
    String scope = null;
    for (AnnotationMirror annotationMirror : annotations ) {
        String declaredScope = null;
        DeclaredType annotationType = annotationMirror.getAnnotationType();
        Element annotationElement = annotationType.asElement();
        if ( annotationElement instanceof TypeElement ){
            TypeElement annotation = (TypeElement)annotationElement;
            scopeChecker.init(annotation, helper );
            if ( scopeChecker.check() ){
                declaredScope = annotation.getQualifiedName().toString();
            }
            normalScopeChecker.init( annotation, helper );
            if ( normalScopeChecker.check() ){
                declaredScope = annotation.getQualifiedName().toString();
            }
            if ( declaredScope != null ){
                if ( !singleScopeRequired ){
                    return declaredScope;
                }
                if ( scope != null ){
                    throw new CdiException(NbBundle.getMessage(
                            ParameterInjectionPointLogic.class, 
                            "ERR_SeveralScopes"));                      // NOI18N
                }
                else {
                    scope = declaredScope;
                }
            }
        }
    }
    return scope;
}