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

The following examples show how to use javax.lang.model.element.VariableElement#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: MethodExtractorUtils.java    From litho with Apache License 2.0 6 votes vote down vote up
private static List<AnnotationSpec> getExternalAnnotations(VariableElement param) {
  final List<? extends AnnotationMirror> annotationMirrors = param.getAnnotationMirrors();
  final List<AnnotationSpec> annotations = new ArrayList<>();

  for (AnnotationMirror annotationMirror : annotationMirrors) {
    if (annotationMirror.getAnnotationType().toString().startsWith(COMPONENTS_PACKAGE)) {
      continue;
    }

    final AnnotationSpec.Builder annotationSpec =
        AnnotationSpec.builder(
            ClassName.bestGuess(annotationMirror.getAnnotationType().toString()));

    Map<? extends ExecutableElement, ? extends AnnotationValue> elementValues =
        annotationMirror.getElementValues();
    for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> elementValue :
        elementValues.entrySet()) {
      annotationSpec.addMember(
          elementValue.getKey().getSimpleName().toString(), elementValue.getValue().toString());
    }

    annotations.add(annotationSpec.build());
  }

  return annotations;
}
 
Example 2
Source File: Utils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static void populateParam(CompilationController controller, VariableElement paramEl, ParamModel paramModel) {
    paramModel.setParamType(paramEl.asType().toString());
    TypeElement paramAnotationEl = controller.getElements().getTypeElement("javax.jws.WebParam"); //NOI18N
    List<? extends AnnotationMirror> paramAnnotations = paramEl.getAnnotationMirrors();
    for (AnnotationMirror anMirror : paramAnnotations) {
        if (controller.getTypes().isSameType(paramAnotationEl.asType(), anMirror.getAnnotationType())) {
            Map<? extends ExecutableElement, ? extends AnnotationValue> expressions = anMirror.getElementValues();
            for(Entry<? extends ExecutableElement, ? extends AnnotationValue> entry:
                expressions.entrySet()) 
            {
                ExecutableElement ex = entry.getKey();
                AnnotationValue value = entry.getValue();
                if (ex.getSimpleName().contentEquals("name")) { //NOI18N
                    paramModel.name = (String)value.getValue();
                } else if (ex.getSimpleName().contentEquals("partName")) { //NOI18N
                    paramModel.setPartName((String)value.getValue());
                } else if (ex.getSimpleName().contentEquals("targetNamespace")) { //NOI18N
                    paramModel.setTargetNamespace((String)value.getValue());
                } else if (ex.getSimpleName().contentEquals("mode")) { //NOI18N
                    paramModel.setMode(Mode.valueOf(value.getValue().toString()));
                }
            }
        }
    }
}
 
Example 3
Source File: EntityMetaFactory.java    From doma with Apache License 2.0 6 votes vote down vote up
void validateFieldAnnotation(VariableElement fieldElement, EntityMeta entityMeta) {
  TypeElement foundAnnotationTypeElement = null;
  for (AnnotationMirror annotation : fieldElement.getAnnotationMirrors()) {
    DeclaredType declaredType = annotation.getAnnotationType();
    TypeElement typeElement = ctx.getMoreTypes().toTypeElement(declaredType);
    if (typeElement.getAnnotation(EntityField.class) != null) {
      if (foundAnnotationTypeElement != null) {
        throw new AptException(
            Message.DOMA4086,
            fieldElement,
            new Object[] {
              foundAnnotationTypeElement.getQualifiedName(), typeElement.getQualifiedName(),
            });
      }
      foundAnnotationTypeElement = typeElement;
    }
  }
}
 
Example 4
Source File: EmbeddableMetaFactory.java    From doma with Apache License 2.0 6 votes vote down vote up
void validateFieldAnnotation(VariableElement fieldElement, EmbeddableMeta embeddableMeta) {
  TypeElement foundAnnotationTypeElement = null;
  for (AnnotationMirror annotation : fieldElement.getAnnotationMirrors()) {
    DeclaredType declaredType = annotation.getAnnotationType();
    TypeElement typeElement = ctx.getMoreTypes().toTypeElement(declaredType);
    if (typeElement.getAnnotation(EntityField.class) != null) {
      if (foundAnnotationTypeElement != null) {
        throw new AptException(
            Message.DOMA4288,
            fieldElement,
            new Object[] {
              foundAnnotationTypeElement.getQualifiedName(), typeElement.getQualifiedName()
            });
      }
      foundAnnotationTypeElement = typeElement;
    }
  }
}
 
Example 5
Source File: ElementTo.java    From sundrio with Apache License 2.0 6 votes vote down vote up
public Property apply(final VariableElement variableElement) {
    String name = variableElement.getSimpleName().toString();

    TypeRef type = MIRROR_TO_TYPEREF.apply(variableElement.asType());
    List<AnnotationRef> annotations = new ArrayList<AnnotationRef>();
    for (AnnotationMirror annotationMirror : variableElement.getAnnotationMirrors()) {
            annotations.add(ANNOTATION_REF.apply(annotationMirror));
    }

    return new PropertyBuilder()
            .withName(name)
            .withTypeRef(type)
            .withAnnotations(annotations)
            .withModifiers(TypeUtils.modifiersToInt(variableElement.getModifiers()))
            .build();
}
 
Example 6
Source File: FieldInfo.java    From CallBuilder with Apache License 2.0 6 votes vote down vote up
static FieldInfo from(Elements elementUtils, VariableElement parameter) {
  FieldStyle style = null;

  // Look for style field on the @BuilderField annotation. If the annotation is
  // present, the value of that field overrides the default set above.
  for (AnnotationMirror ann : parameter.getAnnotationMirrors()) {
    if (ann.getAnnotationType().toString()
        .equals(BuilderField.class.getCanonicalName())) {
      for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> annEl :
           ann.getElementValues().entrySet()) {
        if ("style".equals(annEl.getKey().getSimpleName().toString())) {
          style = FieldStyle.fromStyleClass((DeclaredType) annEl.getValue().getValue());
        }
      }
    }
  }

  return new FieldInfo(parameter, style);
}
 
Example 7
Source File: ToothpickProcessor.java    From toothpick with Apache License 2.0 6 votes vote down vote up
/**
 * Lookup both {@link javax.inject.Qualifier} and {@link javax.inject.Named} to provide the name
 * of an injection.
 *
 * @param element the element for which a qualifier is to be found.
 * @return the name of this element or null if it has no qualifier annotations.
 */
private String findQualifierName(VariableElement element) {
  String name = null;
  if (element.getAnnotationMirrors().isEmpty()) {
    return name;
  }

  for (AnnotationMirror annotationMirror : element.getAnnotationMirrors()) {
    TypeElement annotationTypeElement =
        (TypeElement) annotationMirror.getAnnotationType().asElement();
    if (isSameType(annotationTypeElement, "javax.inject.Named")) {
      checkIfAlreadyHasName(element, name);
      name = getValueOfAnnotation(annotationMirror);
    } else if (annotationTypeElement.getAnnotation(javax.inject.Qualifier.class) != null) {
      checkIfAlreadyHasName(element, name);
      name = annotationTypeElement.getQualifiedName().toString();
    }
  }
  return name;
}
 
Example 8
Source File: PaperParcelProcessingStep.java    From paperparcel with Apache License 2.0 6 votes vote down vote up
private void printMessages(PaperParcelDescriptor.NonReadableFieldsException e) {
  for (VariableElement nonReadableField : e.nonReadableFields()) {
    String fieldName = nonReadableField.getSimpleName().toString();
    String errorMessage = ErrorMessages.FIELD_NOT_READABLE;
if (waitForLombok){
      for (AnnotationMirror mirror : nonReadableField.getAnnotationMirrors())
        if (mirror.toString().contains(LOMBOK_GETTER_ANNOTATION) &&
            mirror.toString().contains(LOMBOK_ACCESS_LEVEL_NONE)) {
          errorMessage = ErrorMessages.FIELD_NOT_READABLE_LOMBOK_GETTER_ACCESS_LEVEL_NONE;
          break;
        }
    }

    messager.printMessage(Diagnostic.Kind.ERROR,
        String.format(errorMessage,
            asType(nonReadableField.getEnclosingElement()).getQualifiedName(),
            fieldName,
            buildExcludeRulesChecklist()),
        nonReadableField);
  }
}
 
Example 9
Source File: PaperParcelProcessingStep.java    From paperparcel with Apache License 2.0 6 votes vote down vote up
private boolean hasNoFieldsWithLombokSetterAccessLevelNone(PaperParcelDescriptor.NonWritableFieldsException e) {

    // make a set of all VariableElements present in method parameter
    Set<VariableElement> elements = new HashSet<>();
    for (ImmutableList<VariableElement> variableElements : e.allNonWritableFieldsMap().values()) {
      for (VariableElement variableElement : variableElements) {
        elements.add(variableElement);
      }
    }
    for (VariableElement nonWritableField : elements) {
      for (AnnotationMirror mirror : nonWritableField.getAnnotationMirrors())
        if (mirror.toString().contains(LOMBOK_SETTER_ANNOTATION) &&
            mirror.toString().contains(LOMBOK_ACCESS_LEVEL_NONE)) {
          return false;
        }
    }
    return true;
  }
 
Example 10
Source File: ColumnElement.java    From Ollie with Apache License 2.0 5 votes vote down vote up
public ColumnElement(Registry registry, TypeElement enclosingType, VariableElement element) {
	this.element = element;
	this.column = element.getAnnotation(Column.class);
	this.enclosingType = enclosingType;
	this.deserializedType = registry.getElements().getTypeElement(element.asType().toString());

	final TypeAdapterElement typeAdapterElement = registry.getTypeAdapterElement(deserializedType);
	final TypeElement modelElement = registry.getElements().getTypeElement("ollie.Model");
	final DeclaredType modelType = registry.getTypes().getDeclaredType(modelElement);
	isModel = registry.getTypes().isAssignable(element.asType(), modelType);

	if (isModel) {
		final Table table = deserializedType.getAnnotation(Table.class);
		serializedType = registry.getElements().getTypeElement(Long.class.getName());
		modelTableName = table.value();
	} else if (typeAdapterElement != null) {
		serializedType = typeAdapterElement.getSerializedType();
	} else {
		serializedType = deserializedType;
	}

	this.sqlType = SQL_TYPE_MAP.get(getSerializedQualifiedName());

	List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors();
	for (AnnotationMirror annotationMirror : annotationMirrors) {
		try {
			Class annotationClass = Class.forName(annotationMirror.getAnnotationType().toString());
			annotations.put(annotationClass, element.getAnnotation(annotationClass));
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}
 
Example 11
Source File: ConfigFieldParser.java    From aircon with MIT License 5 votes vote down vote up
private void extractCustomConfigTypeAnnotation(final VariableElement element) {
	final List<? extends AnnotationMirror> elementAnnotations = element.getAnnotationMirrors();
	for (AnnotationMirror annotationMirror : elementAnnotations) {
		if (hasConfigTypeAnnotation(annotationMirror)) {
			mConfigAnnotation = new CustomConfigAnnotationParser(mTypes, annotationMirror);
		}
	}
}
 
Example 12
Source File: AutoParcelProcessor.java    From auto-parcel with Apache License 2.0 5 votes vote down vote up
private ImmutableSet<String> getAnnotations(VariableElement element) {
    ImmutableSet.Builder<String> builder = ImmutableSet.builder();
    for (AnnotationMirror annotation : element.getAnnotationMirrors()) {
        builder.add(annotation.getAnnotationType().asElement().getSimpleName().toString());
    }

    return builder.build();
}
 
Example 13
Source File: Names.java    From featured with Apache License 2.0 5 votes vote down vote up
private static TypeName applyAnnotations(TypeName typeName, VariableElement param) {
    List<? extends AnnotationMirror> annotationMirrors = param.getAnnotationMirrors();
    if (annotationMirrors.size() > 0) {
        List<AnnotationSpec> annotationSpecs =
                new ArrayList<>(annotationMirrors.size());
        for (AnnotationMirror annotationMirror : annotationMirrors) {
            annotationSpecs.add(AnnotationSpec.get(annotationMirror));
        }
        typeName = typeName.annotated(annotationSpecs);
    }
    return typeName;
}
 
Example 14
Source File: PropertyProcessor.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected AnnotationMirror findPropertyAnnotation(VariableElement element)
{
	AnnotationMirror propertyAnnotation = null;
	List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors();
	for (AnnotationMirror annotation : annotationMirrors)
	{
		if (annotation.getAnnotationType().toString().equals(Property.class.getCanonicalName()))
		{
			propertyAnnotation = annotation;
			break;
		}
	}
	return propertyAnnotation;
}
 
Example 15
Source File: Aptools.java    From Java-9-Programming-By-Example with MIT License 5 votes vote down vote up
/**
 * Get an array of lists containing the annotations of the arguments.
 */
@Transition(from = "MethodTool", end = true)
public List<? extends AnnotationMirror>[] getParameterAnnotations() {
  @SuppressWarnings("unchecked")
  List<? extends AnnotationMirror>[] annotationMirrorss = new List[getTheNumberOfParameters()];
  int i = 0;
  for (VariableElement parameterElement : methodElement.getParameters()) {
    annotationMirrorss[i] = parameterElement.getAnnotationMirrors();
    i++;
  }
  return annotationMirrorss;
}
 
Example 16
Source File: ValueParser.java    From dataenum with Apache License 2.0 5 votes vote down vote up
private static boolean isAnnotationPresent(
    VariableElement parameterElement, Function<AnnotationMirror, Boolean> criterion) {
  for (AnnotationMirror annotation : parameterElement.getAnnotationMirrors()) {
    if (criterion.apply(annotation)) {
      return true;
    }
  }
  return false;
}
 
Example 17
Source File: ClassVisitorDriverFromElement.java    From buck with Apache License 2.0 4 votes vote down vote up
private void generateBridge(ExecutableElement fromMethod, ExecutableElement toMethod) {
  ExecutableType toErasure = (ExecutableType) types.erasure(toMethod.asType());
  String bridgeDescriptor = descriptorFactory.getDescriptor(toErasure);
  if (bridgedDescriptors.get(toMethod.getSimpleName()).contains(bridgeDescriptor)) {
    return;
  }

  innerClassesTable.addTypeReferences(toErasure);

  String[] exceptions =
      toErasure.getThrownTypes().stream()
          .map(descriptorFactory::getInternalName)
          .toArray(String[]::new);

  MethodVisitor methodVisitor =
      visitor.visitMethod(
          getBridgeAccessFlags(fromMethod),
          toMethod.getSimpleName().toString(),
          bridgeDescriptor,
          signatureFactory.getSignature(toErasure),
          exceptions);
  if (methodVisitor != null) {
    List<? extends VariableElement> fromMethodParameters = fromMethod.getParameters();
    for (int i = 0; i < fromMethodParameters.size(); i++) {
      VariableElement fromMethodParameter = fromMethodParameters.get(i);
      List<? extends AnnotationMirror> annotations =
          fromMethodParameter.getAnnotationMirrors();
      innerClassesTable.addTypeReferences(annotations);
      visitParameter(
          i,
          fromMethodParameter,
          fromMethodParameter.getSimpleName(),
          accessFlagsUtils.getAccessFlags(fromMethodParameter) | Opcodes.ACC_SYNTHETIC,
          annotations,
          methodVisitor);
    }
    innerClassesTable.addTypeReferences(fromMethod.getAnnotationMirrors());
    visitAnnotations(fromMethod, methodVisitor::visitAnnotation);
    methodVisitor.visitEnd();

    bridgedDescriptors.put(toMethod.getSimpleName(), bridgeDescriptor);
  }
}
 
Example 18
Source File: OperationAnnotationValidator.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
public void checkMethodArgsAreValid(final TypeElement annotationElement, final ExecutableElement methodElement)
{
    Elements elementUtils = processingEnv.getElementUtils();
    TypeElement paramElement = elementUtils.getTypeElement(OPERATION_PARAM_CLASS_NAME);

    for (VariableElement varElem : methodElement.getParameters())
    {
        if(!isValidType(varElem.asType(), false))
        {
            processingEnv.getMessager()
                         .printMessage(Diagnostic.Kind.ERROR,
                                       "@"
                                       + paramElement.getSimpleName()
                                       + " cannot be applied to variables of type "
                                       + varElem.asType().toString(),
                                       methodElement
                                      );
        }
        String name = varElem.getSimpleName().toString();
        final List<? extends AnnotationMirror> annotationMirrors = varElem.getAnnotationMirrors();
        AnnotationMirror paramAnnotation = null;
        for(AnnotationMirror annotationMirror : annotationMirrors)
        {
            if(annotationMirror.getAnnotationType().asElement().equals(paramElement))
            {
                paramAnnotation = annotationMirror;
                break;
            }
        }
        if(paramAnnotation == null)
        {
            processingEnv.getMessager()
                    .printMessage(Diagnostic.Kind.ERROR,
                                  "Argument " + name + " of " + methodElement.getSimpleName()
                                  + " must be annotated with @"
                                  + paramElement.getSimpleName()
                                  + " or the method should not be annotated with @"
                                  + annotationElement.getSimpleName()
                                 );
        }
        else
        {
            String paramName = null;

            for(Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : paramAnnotation.getElementValues().entrySet())
            {
                if(entry.getKey().getSimpleName().toString().equals("name"))
                {
                    paramName = String.valueOf(entry.getValue().getValue());
                }
            }

            if(!name.equals(paramName))
            {
                processingEnv.getMessager()
                        .printMessage(Diagnostic.Kind.ERROR,
                                      "Argument " + name + " of " + methodElement.getSimpleName()
                                      + " is annotated with @"
                                      + paramElement.getSimpleName()
                                      + "( name = \""
                                      + paramName
                                      + "\") the name must match the actual parameter name, i.e. it should read @"

                                      + paramElement.getSimpleName()
                                      + "( name = \""
                                      + name
                                      + "\")"
                                     );
            }

        }
    }
}
 
Example 19
Source File: GraphNodeVerifier.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private void scanFields(TypeElement node) {
    TypeElement currentClazz = node;
    do {
        for (VariableElement field : ElementFilter.fieldsIn(currentClazz.getEnclosedElements())) {
            Set<Modifier> modifiers = field.getModifiers();
            if (modifiers.contains(STATIC) || modifiers.contains(TRANSIENT)) {
                continue;
            }

            List<? extends AnnotationMirror> annotations = field.getAnnotationMirrors();

            boolean isNonOptionalInput = findAnnotationMirror(annotations, Input) != null;
            boolean isOptionalInput = findAnnotationMirror(annotations, OptionalInput) != null;
            boolean isSuccessor = findAnnotationMirror(annotations, Successor) != null;

            if (isNonOptionalInput || isOptionalInput) {
                if (findAnnotationMirror(annotations, Successor) != null) {
                    throw new ElementException(field, "Field cannot be both input and successor");
                } else if (isNonOptionalInput && isOptionalInput) {
                    throw new ElementException(field, "Inputs must be either optional or non-optional");
                } else if (isAssignableWithErasure(field, NodeInputList)) {
                    if (modifiers.contains(FINAL)) {
                        throw new ElementException(field, "Input list field must not be final");
                    }
                    if (modifiers.contains(PUBLIC)) {
                        throw new ElementException(field, "Input list field must not be public");
                    }
                } else {
                    if (!isAssignableWithErasure(field, Node) && field.getKind() == ElementKind.INTERFACE) {
                        throw new ElementException(field, "Input field type must be an interface or assignable to Node");
                    }
                    if (modifiers.contains(FINAL)) {
                        throw new ElementException(field, "Input field must not be final");
                    }
                    if (modifiers.contains(PUBLIC)) {
                        throw new ElementException(field, "Input field must not be public");
                    }
                }
            } else if (isSuccessor) {
                if (isAssignableWithErasure(field, NodeSuccessorList)) {
                    if (modifiers.contains(FINAL)) {
                        throw new ElementException(field, "Successor list field must not be final");
                    }
                    if (modifiers.contains(PUBLIC)) {
                        throw new ElementException(field, "Successor list field must not be public");
                    }
                } else {
                    if (!isAssignableWithErasure(field, Node)) {
                        throw new ElementException(field, "Successor field must be a Node type");
                    }
                    if (modifiers.contains(FINAL)) {
                        throw new ElementException(field, "Successor field must not be final");
                    }
                    if (modifiers.contains(PUBLIC)) {
                        throw new ElementException(field, "Successor field must not be public");
                    }
                }

            } else {
                if (isAssignableWithErasure(field, Node) && !field.getSimpleName().contentEquals("Null")) {
                    throw new ElementException(field, "Node field must be annotated with @" + Input.getSimpleName() + ", @" + OptionalInput.getSimpleName() + " or @" + Successor.getSimpleName());
                }
                if (isAssignableWithErasure(field, NodeInputList)) {
                    throw new ElementException(field, "NodeInputList field must be annotated with @" + Input.getSimpleName() + " or @" + OptionalInput.getSimpleName());
                }
                if (isAssignableWithErasure(field, NodeSuccessorList)) {
                    throw new ElementException(field, "NodeSuccessorList field must be annotated with @" + Successor.getSimpleName());
                }
                if (modifiers.contains(PUBLIC) && !modifiers.contains(FINAL)) {
                    throw new ElementException(field, "Data field must be final if public");
                }
            }
        }
        currentClazz = getSuperType(currentClazz);
    } while (!isObject(getSuperType(currentClazz).asType()));
}
 
Example 20
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);
}