Java Code Examples for javax.lang.model.element.Element#getAnnotationMirrors()

The following examples show how to use javax.lang.model.element.Element#getAnnotationMirrors() . 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: 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 2
Source File: AnnotationHandle.java    From Mixin with MIT License 6 votes vote down vote up
protected static AnnotationMirror getAnnotation(Element elem, Class<? extends Annotation> annotationClass) {
    if (elem == null) {
        return null;
    }
    
    List<? extends AnnotationMirror> annotations = elem.getAnnotationMirrors();
    
    if (annotations == null) {
        return null;
    }
    
    for (AnnotationMirror annotation : annotations) {
        Element element = annotation.getAnnotationType().asElement();
        if (!(element instanceof TypeElement)) {
            continue;
        }
        TypeElement annotationElement = (TypeElement)element;
        if (annotationElement.getQualifiedName().contentEquals(annotationClass.getName())) {
            return annotation;
        }
    }
    
    return null;
}
 
Example 3
Source File: ParameterInjectionPointLogic.java    From netbeans with Apache License 2.0 6 votes vote down vote up
static String getDeclaredScope( Element element , 
        AnnotationModelHelper helper ) throws CdiException
{
    List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors();
    ScopeChecker scopeChecker = ScopeChecker.get();
    NormalScopeChecker normalScopeChecker = NormalScopeChecker.get();
    String scope = getDeclaredScope(helper, annotationMirrors, scopeChecker, 
            normalScopeChecker, true);
    if ( scope != null ){
        return scope;
    }
    
    annotationMirrors = helper.getCompilationController().getElements().
        getAllAnnotationMirrors( element );
    return getDeclaredScope(helper, annotationMirrors, scopeChecker, 
            normalScopeChecker, false );
}
 
Example 4
Source File: ManagedAttributeValueTypeValidator.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
private boolean isAbstract(final TypeElement annotationElement, final Element typeElement)
{
    for (AnnotationMirror annotation : typeElement.getAnnotationMirrors())
    {
        if (annotation.getAnnotationType().asElement().equals(annotationElement))
        {

            Map<? extends ExecutableElement, ? extends AnnotationValue> annotationValues =
                    processingEnv.getElementUtils().getElementValuesWithDefaults(annotation);
            for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> element : annotationValues.entrySet())
            {
                if ("isAbstract".contentEquals(element.getKey().getSimpleName()))
                {
                    return element.getValue().getValue().equals(Boolean.TRUE);
                }
            }
            break;
        }
    }
    return false;
}
 
Example 5
Source File: InlineAnnotationReaderImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets all the annotations on the given declaration.
 */
private Annotation[] getAllAnnotations(Element decl, Locatable srcPos) {
    List<Annotation> r = new ArrayList<Annotation>();

    for( AnnotationMirror m : decl.getAnnotationMirrors() ) {
        try {
            String fullName = ((TypeElement) m.getAnnotationType().asElement()).getQualifiedName().toString();
            Class<? extends Annotation> type =
                SecureLoader.getClassClassLoader(getClass()).loadClass(fullName).asSubclass(Annotation.class);
            Annotation annotation = decl.getAnnotation(type);
            if(annotation!=null)
                r.add( LocatableAnnotation.create(annotation,srcPos) );
        } catch (ClassNotFoundException e) {
            // just continue
        }
    }

    return r.toArray(new Annotation[r.size()]);
}
 
Example 6
Source File: ToKeywords.java    From sundrio with Apache License 2.0 6 votes vote down vote up
public Set<String> apply(Element element) {
    Set<String> keywords = new HashSet<String>();
    for (AnnotationMirror mirror : element.getAnnotationMirrors()) {
        if (mirror.getAnnotationType().asElement().equals(KEYWORD)) {
            keywords.addAll(TypeDefUtils.toClassNames(mirror.getElementValues().get(VALUE).getValue()));
        }


        for (AnnotationMirror innerMirror : mirror.getAnnotationType().asElement().getAnnotationMirrors()) {
            if (innerMirror.getAnnotationType().asElement().equals(KEYWORD)) {
                if (innerMirror.getElementValues().containsKey(VALUE)) {
                    keywords.addAll(TypeDefUtils.toClassNames(innerMirror.getElementValues().get(VALUE).getValue()));
                } else {
                    keywords.addAll(TypeDefUtils.toClassNames(mirror.getAnnotationType().asElement().toString()));
                }
            }
        }
    }
    return keywords;
}
 
Example 7
Source File: Utils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static String getAnnotationValue(Element element, String annotationType, String paramName) {
    for (AnnotationMirror annotation : element.getAnnotationMirrors()) {
        if (annotation.getAnnotationType().toString().equals(annotationType)) {
            for (ExecutableElement key : annotation.getElementValues().keySet()) {
                //System.out.println("key = " + key.getSimpleName());
                if (key.getSimpleName().toString().equals(paramName)) {
                    String value = annotation.getElementValues().get(key).toString();
                    value = stripQuotes(value);

                    return value;
                }
            }
        }
    }

    return "";
}
 
Example 8
Source File: Utils.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Return true if the given Element is deprecated for removal.
 *
 * @param e the Element to check.
 * @return true if the given Element is deprecated for removal.
 */
public boolean isDeprecatedForRemoval(Element e) {
    List<? extends AnnotationMirror> annotationList = e.getAnnotationMirrors();
    JavacTypes jctypes = ((DocEnvImpl) configuration.docEnv).toolEnv.typeutils;
    for (AnnotationMirror anno : annotationList) {
        if (jctypes.isSameType(anno.getAnnotationType().asElement().asType(), getDeprecatedType())) {
            Map<? extends ExecutableElement, ? extends AnnotationValue> pairs = anno.getElementValues();
            if (!pairs.isEmpty()) {
                for (ExecutableElement element : pairs.keySet()) {
                    if (element.getSimpleName().contentEquals("forRemoval")) {
                        return Boolean.parseBoolean((pairs.get(element)).toString());
                    }
                }
            }
        }
    }
    return false;
}
 
Example 9
Source File: ElementUtils.java    From spring-init with Apache License 2.0 6 votes vote down vote up
public List<String> getStringsFromAnnotation(Element type, String annotation,
		String attribute) {
	Set<String> list = new HashSet<>();
	for (AnnotationMirror mirror : type.getAnnotationMirrors()) {
		if (((TypeElement) mirror.getAnnotationType().asElement()).getQualifiedName()
				.toString().equals(annotation)) {
			list.addAll(getStringsFromAnnotation(mirror, attribute));
		}
		AnnotationMirror meta = getAnnotation(mirror.getAnnotationType().asElement(),
				annotation);
		if (meta != null) {
			list.addAll(getStringsFromAnnotation(meta, attribute));
		}
	}
	return new ArrayList<>(list);
}
 
Example 10
Source File: HashCodeValidator.java    From epoxy with Apache License 2.0 5 votes vote down vote up
/**
 * Only works for classes in the module since AutoValue has a retention of Source so it is
 * discarded after compilation.
 */
private boolean isAutoValueType(Element element) {
  for (AnnotationMirror annotationMirror : element.getAnnotationMirrors()) {
    DeclaredType annotationType = annotationMirror.getAnnotationType();
    boolean isAutoValue = isSubtypeOfType(annotationType, "com.google.auto.value.AutoValue");
    if (isAutoValue) {
      return true;
    }
  }
  return false;
}
 
Example 11
Source File: AttributeFieldValidation.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv)
{
    Elements elementUtils = processingEnv.getElementUtils();
    Types typeUtils = processingEnv.getTypeUtils();

    TypeElement annotationElement = elementUtils.getTypeElement(MANAGED_ATTRIBUTE_FIELD_CLASS_NAME);
    for (Element e : roundEnv.getElementsAnnotatedWith(annotationElement))
    {
        for(AnnotationMirror am : e.getAnnotationMirrors())
        {
            if(typeUtils.isSameType(am.getAnnotationType(), annotationElement.asType()))
            {
                for(Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : am.getElementValues().entrySet())
                {
                    String elementName = entry.getKey().getSimpleName().toString();
                    if(elementName.equals("beforeSet") || elementName.equals("afterSet"))
                    {
                        String methodName = entry.getValue().getValue().toString();
                        if(!"".equals(methodName))
                        {
                            TypeElement parent = (TypeElement) e.getEnclosingElement();
                            if(!containsMethod(parent, methodName))
                            {
                                processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                                                                         "Could not find method '"
                                                                         + methodName
                                                                         + "' which is defined as the "
                                                                         + elementName
                                                                         + " action", e);

                            }
                        }
                    }
                }
            }
        }
    }
    return false;
}
 
Example 12
Source File: WSITRefactoringPlugin.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected static boolean isWebSvcFromWsdl(Element element){
    for (AnnotationMirror ann : element.getAnnotationMirrors()) {
        if (WS_ANNOTATION.equals(((TypeElement) ann.getAnnotationType().asElement()).getQualifiedName())) {
            for (ExecutableElement annVal : ann.getElementValues().keySet()) {
                if (WSDL_LOCATION_ELEMENT.equals(annVal.getSimpleName().toString())){
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 13
Source File: AbstractRestAnnotationProcessor.java    From RADL with Apache License 2.0 5 votes vote down vote up
protected Collection<String> valueOf(TypeElement annotation, Element element, String property) {
  if (annotation == null) {
    return null;
  }
  Name annotationClassName = annotation.getQualifiedName();
  for (AnnotationMirror annotationMirror : element.getAnnotationMirrors()) {
    TypeElement annotationElement = (TypeElement)annotationMirror.getAnnotationType().asElement();
    if (annotationElement.getQualifiedName().contentEquals(annotationClassName)) {
      return valueOf(annotationMirror, property);
    }
  }
  return null;
}
 
Example 14
Source File: LayerGenerationException.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static AnnotationMirror findAnnotationMirror(Element element, ProcessingEnvironment processingEnv, Class<? extends Annotation> annotation) {
    for (AnnotationMirror ann : element.getAnnotationMirrors()) {
        if (processingEnv.getElementUtils().getBinaryName((TypeElement) ann.getAnnotationType().asElement()).
                contentEquals(annotation.getName())) {
            return ann;
        }
    }
    return null;
}
 
Example 15
Source File: ProcessorUtils.java    From pandroid with Apache License 2.0 5 votes vote down vote up
public static AnnotationMirror getAnnotationMirror(Element element, Class<?> clazz) {
    String clazzName = clazz.getName();
    for(AnnotationMirror m : element.getAnnotationMirrors()) {
        if(m.getAnnotationType().toString().equals(clazzName)) {
            return m;
        }
    }
    return null;
}
 
Example 16
Source File: SPIProcessor.java    From core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void handleSearchIndexElement(final Element element) {
    List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors();
    for (AnnotationMirror mirror : annotationMirrors) {
        final String annotationType = mirror.getAnnotationType().toString();

        if (annotationType.equals(NameToken.class.getName())) {
            NameToken nameToken = element.getAnnotation(NameToken.class);
            AccessControl accessControl = element.getAnnotation(AccessControl.class);
            SearchIndex searchIndex = element.getAnnotation(SearchIndex.class);
            OperationMode operationMode = element.getAnnotation(OperationMode.class);

            if (accessControl != null) {
                boolean standalone = true;
                boolean domain = true;
                String[] keywords = null;
                boolean include = true;
                if (searchIndex != null) {
                    keywords = searchIndex.keywords();
                    include = !searchIndex.exclude();
                }
                if (operationMode != null) {
                    standalone = operationMode.value() == OperationMode.Mode.STANDALONE;
                    domain = operationMode.value() == OperationMode.Mode.DOMAIN;
                }
                if (include) {
                    // excluded presenters are not part of the metadata!
                    SearchIndexMetaData searchIndexMetaData = new SearchIndexMetaData(nameToken.value()[0], standalone,
                            domain, accessControl.resources(), keywords);
                    searchIndexDeclarations.add(searchIndexMetaData);
                }
            }
        }
    }
}
 
Example 17
Source File: ConfigurationAnnotations.java    From dagger2-sample with Apache License 2.0 5 votes vote down vote up
/** Returns the first type that specifies this' nullability, or absent if none. */
static Optional<DeclaredType> getNullableType(Element element) {
  List<? extends AnnotationMirror> mirrors = element.getAnnotationMirrors();
  for (AnnotationMirror mirror : mirrors) {
    if (mirror.getAnnotationType().asElement().getSimpleName().toString().equals("Nullable")) {
      return Optional.of(mirror.getAnnotationType());
    }
  }
  return Optional.absent();
}
 
Example 18
Source File: EntityMappingsUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static boolean hasFieldAccess(AnnotationModelHelper helper, List<? extends Element> elements) {
    for (Element element : ElementFilter.methodsIn(elements)) {
        for (AnnotationMirror annotation : element.getAnnotationMirrors()) {
            String annTypeName = helper.getAnnotationTypeName(annotation.getAnnotationType());
            if (annTypeName != null && ORM_ANNOTATIONS.contains(annTypeName)) {
                return false;
            }
        }
    }
    // if we got here, no methods were annotated with JPA ORM annotations
    // then either fields are annotated, or there are no annotations in the class
    // (in which case the default -- field access -- applies)
    return true;
}
 
Example 19
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static AnnotationMirror findAnnotation(Element element, String annotationClass){
    for (AnnotationMirror ann : element.getAnnotationMirrors()){
        if (annotationClass.equals(ann.getAnnotationType().toString())){
            return ann;
        }
    }
    
    return null;
}
 
Example 20
Source File: StateProcessor.java    From android-state with Eclipse Public License 1.0 4 votes vote down vote up
private BundlerWrapper getBundlerWrapper(Element field) {
    for (AnnotationMirror annotationMirror : field.getAnnotationMirrors()) {
        if (!isStateAnnotation(annotationMirror)) {
            continue;
        }

        Map<? extends ExecutableElement, ? extends AnnotationValue> elementValues = annotationMirror.getElementValues();
        for (ExecutableElement executableElement : elementValues.keySet()) {
            if ("value".equals(executableElement.getSimpleName().toString())) {
                Object value = elementValues.get(executableElement).getValue(); // bundler class
                if (value == null) {
                    continue;
                }
                TypeName bundlerName = ClassName.get(mElementUtils.getTypeElement(value.toString()));
                TypeName genericName = null;

                try {
                    // gets the generic type Data from `class MyBundler implements Bundler<Data> {}`
                    List<? extends TypeMirror> interfaces = mElementUtils.getTypeElement(value.toString()).getInterfaces();
                    for (TypeMirror anInterface : interfaces) {
                        if (isAssignable(mTypeUtils.erasure(anInterface), BUNDLER_CLASS_NAME)) {
                            List<? extends TypeMirror> typeArguments = ((DeclaredType) anInterface).getTypeArguments();
                            if (typeArguments != null && typeArguments.size() >= 1) {
                                TypeMirror genericTypeMirror = typeArguments.get(0);
                                String genericString = genericTypeMirror.toString();

                                // this check is necessary for returned types like: List<? extends String> -> remove "? extends"
                                if (genericString.contains("<? extends ")) {
                                    String innerType = genericString.substring(genericString.indexOf("<? extends ") + 11, genericString.length() - 1);

                                    // if it's a Parcelable, then we need to know the correct type for the bundler, e.g. List<ParcelableImpl> for parcelable list bundler
                                    if (PARCELABLE_CLASS_NAME.equals(innerType)) {
                                        InsertedTypeResult insertedType = getInsertedType(field, true);
                                        if (insertedType != null) {
                                            innerType = insertedType.mTypeMirror.toString();
                                        }
                                    }

                                    ClassName erasureClassName = ClassName.bestGuess(mTypeUtils.erasure(genericTypeMirror).toString());
                                    genericName = ParameterizedTypeName.get(erasureClassName, ClassName.bestGuess(innerType));
                                } else {
                                    genericName = ClassName.get(genericTypeMirror);
                                }
                            }
                        }
                    }
                } catch (Exception ignored) {
                }
                return new BundlerWrapper(bundlerName, genericName == null ? ClassName.get(Object.class) : genericName);
            }
        }
    }
    return null;
}