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

The following examples show how to use javax.lang.model.element.VariableElement#getModifiers() . 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: PubapiVisitor.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a String representation of a variable element with everything
 * necessary to track all public aspects of it in an API.
 * @param e Element to create String for.
 * @return String representation of element.
 */
protected String makeVariableString(VariableElement e) {
    StringBuilder result = new StringBuilder();
    for (Modifier modifier : e.getModifiers()) {
        result.append(modifier.toString());
        result.append(" ");
    }
    result.append(e.asType().toString());
    result.append(" ");
    result.append(e.toString());
    Object value = e.getConstantValue();
    if (value != null) {
        result.append(" = ");
        if (e.asType().toString().equals("char")) {
            int v = (int)value.toString().charAt(0);
            result.append("'\\u"+Integer.toString(v,16)+"'");
        } else {
            result.append(value.toString());
        }
    }
    return result.toString();
}
 
Example 2
Source File: PubapiVisitor.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a String representation of a variable element with everything
 * necessary to track all public aspects of it in an API.
 * @param e Element to create String for.
 * @return String representation of element.
 */
protected String makeVariableString(VariableElement e) {
    StringBuilder result = new StringBuilder();
    for (Modifier modifier : e.getModifiers()) {
        result.append(modifier.toString());
        result.append(" ");
    }
    result.append(e.asType().toString());
    result.append(" ");
    result.append(e.toString());
    Object value = e.getConstantValue();
    if (value != null) {
        result.append(" = ");
        if (e.asType().toString().equals("char")) {
            int v = (int)value.toString().charAt(0);
            result.append("'\\u"+Integer.toString(v,16)+"'");
        } else {
            result.append(value.toString());
        }
    }
    return result.toString();
}
 
Example 3
Source File: PubapiVisitor.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a String representation of a variable element with everything
 * necessary to track all public aspects of it in an API.
 * @param e Element to create String for.
 * @return String representation of element.
 */
protected String makeVariableString(VariableElement e) {
    StringBuilder result = new StringBuilder();
    for (Modifier modifier : e.getModifiers()) {
        result.append(modifier.toString());
        result.append(" ");
    }
    result.append(e.asType().toString());
    result.append(" ");
    result.append(e.toString());
    Object value = e.getConstantValue();
    if (value != null) {
        result.append(" = ");
        if (e.asType().toString().equals("char")) {
            int v = (int)value.toString().charAt(0);
            result.append("'\\u"+Integer.toString(v,16)+"'");
        } else {
            result.append(value.toString());
        }
    }
    return result.toString();
}
 
Example 4
Source File: Environment.java    From sqlitemagic with Apache License 2.0 6 votes vote down vote up
private static void getLocalAndInheritedColumnFields(PackageElement pkg,
                                                     TypeElement type,
                                                     SetMultimap<String, VariableElement> fields) {
  for (TypeMirror superInterface : type.getInterfaces()) {
    getLocalAndInheritedColumnFields(pkg, asTypeElement(superInterface), fields);
  }
  if (type.getSuperclass().getKind() != TypeKind.NONE) {
    // Visit the superclass after superinterfaces so we will always see the implementation of a
    // method after any interfaces that declared it.
    getLocalAndInheritedColumnFields(pkg, asTypeElement(type.getSuperclass()), fields);
  }
  for (VariableElement field : ElementFilter.fieldsIn(type.getEnclosedElements())) {
    final Set<Modifier> modifiers = field.getModifiers();
    if (!modifiers.contains(Modifier.STATIC)) {
      fields.put(field.getSimpleName().toString(), field);
    }
  }
}
 
Example 5
Source File: InjectFieldValidator.java    From dagger2-sample with Apache License 2.0 6 votes vote down vote up
@Override
public ValidationReport<VariableElement> validate(VariableElement fieldElement) {
  ValidationReport.Builder<VariableElement> builder =
      ValidationReport.Builder.about(fieldElement);
  Set<Modifier> modifiers = fieldElement.getModifiers();
  if (modifiers.contains(FINAL)) {
    builder.addItem(FINAL_INJECT_FIELD, fieldElement);
  }

  if (modifiers.contains(PRIVATE)) {
    builder.addItem(PRIVATE_INJECT_FIELD, fieldElement);
  }

  ImmutableSet<? extends AnnotationMirror> qualifiers = getQualifiers(fieldElement);
  if (qualifiers.size() > 1) {
    for (AnnotationMirror qualifier : qualifiers) {
      builder.addItem(MULTIPLE_QUALIFIERS, fieldElement, qualifier);
    }
  }

  return builder.build();
}
 
Example 6
Source File: PubapiVisitor.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a String representation of a variable element with everything
 * necessary to track all public aspects of it in an API.
 * @param e Element to create String for.
 * @return String representation of element.
 */
protected String makeVariableString(VariableElement e) {
    StringBuilder result = new StringBuilder();
    for (Modifier modifier : e.getModifiers()) {
        result.append(modifier.toString());
        result.append(" ");
    }
    result.append(e.asType().toString());
    result.append(" ");
    result.append(e.toString());
    Object value = e.getConstantValue();
    if (value != null) {
        result.append(" = ");
        if (e.asType().toString().equals("char")) {
            int v = (int)value.toString().charAt(0);
            result.append("'\\u"+Integer.toString(v,16)+"'");
        } else {
            result.append(value.toString());
        }
    }
    return result.toString();
}
 
Example 7
Source File: Utils.java    From AirData with MIT License 5 votes vote down vote up
public static boolean isValid(VariableElement element) {
    Set<Modifier> modifiers = element.getModifiers();
    return !modifiers.contains(Modifier.STATIC)
            && !modifiers.contains(Modifier.FINAL)
            && !modifiers.contains(Modifier.TRANSIENT)
            && element.getAnnotation(ColumnIgnore.class) == null;
}
 
Example 8
Source File: ToothpickProcessor.java    From toothpick with Apache License 2.0 5 votes vote down vote up
protected boolean isValidInjectAnnotatedFieldOrParameter(VariableElement variableElement) {
  TypeElement enclosingElement = (TypeElement) variableElement.getEnclosingElement();

  // Verify modifiers.
  Set<Modifier> modifiers = variableElement.getModifiers();
  if (modifiers.contains(PRIVATE)) {
    error(
        variableElement,
        "@Inject annotated fields must be non private : %s#%s",
        enclosingElement.getQualifiedName(),
        variableElement.getSimpleName());
    return false;
  }

  // Verify parentScope modifiers.
  Set<Modifier> parentModifiers = enclosingElement.getModifiers();
  if (parentModifiers.contains(PRIVATE)) {
    error(
        variableElement,
        "@Injected fields in class %s. The class must be non private.",
        enclosingElement.getSimpleName());
    return false;
  }

  if (!isValidInjectedType(variableElement)) {
    return false;
  }
  return true;
}
 
Example 9
Source File: PubapiVisitor.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override @DefinedBy(Api.LANGUAGE_MODEL)
public Void visitVariable(VariableElement e, Void p) {
    if (isNonPrivate(e)) {
        Object constVal = e.getConstantValue();
        String constValStr = null;
        // TODO: This doesn't seem to be entirely accurate. What if I change
        // from, say, 0 to 0L? (And the field is public final static so that
        // it could get inlined.)
        if (constVal != null) {
            if (e.asType().toString().equals("char")) {
                // What type is 'value'? Is it already a char?
                char c = constVal.toString().charAt(0);
                constValStr = "'" + encodeChar(c) + "'";
            } else {
                constValStr = constVal.toString()
                                      .chars()
                                      .mapToObj(PubapiVisitor::encodeChar)
                                      .collect(Collectors.joining("", "\"", "\""));
            }
        }

        PubVar v = new PubVar(e.getModifiers(),
                              TypeDesc.fromType(e.asType()),
                              e.toString(),
                              constValStr);
        collectedApi.variables.put(v.identifier, v);
    }

    // Safe to not recurse here, because the only thing
    // to visit here is the constructor of a variable declaration.
    // If it happens to contain an anonymous inner class (which it might)
    // then this class is never visible outside of the package anyway, so
    // we are allowed to ignore it here.
    return null;
}
 
Example 10
Source File: Validator.java    From AutoBundle with Apache License 2.0 5 votes vote down vote up
static void checkAutoBundleFieldModifier(VariableElement element, boolean hasGetterSetter) {
    Set<Modifier> modifiers = element.getModifiers();
    if (modifiers.contains(Modifier.PRIVATE) && !hasGetterSetter) {
        throw new ProcessingException(
                AutoBundleField.class + " does not support private field without setter/getter.");
    }
}
 
Example 11
Source File: BeanModelBuilder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void addConstant(VariableElement v) {
    Set<Modifier> mods = v.getModifiers();
    if (!(mods.contains(Modifier.FINAL) && mods.contains(Modifier.STATIC))) {
        return;
    }
    
    boolean ok = false;
    
    // check that the return type is the same as this class' type
    if (!compilationInfo.getTypes().isSameType(
            v.asType(), classElement.asType())) {
        // the constant may be primitive & our type the wrapper
        TypeMirror t = v.asType();
        if (t instanceof PrimitiveType) {
            PrimitiveType p = (PrimitiveType)t;
            if (compilationInfo.getTypes().isSameType(
                    compilationInfo.getTypes().boxedClass(p).asType(),
                    classElement.asType())) {
                ok = true;
            }
        } 
        if (!ok) {
            return;
        }
    }
    
    addConstant(v.getSimpleName().toString());
}
 
Example 12
Source File: FieldInjectionPointLogic.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void checkInjectionPoint( VariableElement element ) 
    throws InjectionPointDefinitionError
{
    CompilationController compilationController = getModel().getHelper().
        getCompilationController();
    Tree tree = compilationController.getTrees().getTree( element );
    if ( tree instanceof VariableTree ){
        VariableTree varTree = (VariableTree)tree;
        ExpressionTree initializer = varTree.getInitializer();
        if ( initializer != null ){
            throw new InjectionPointDefinitionError(NbBundle.getMessage( 
                    FieldInjectionPointLogic.class, 
                    "ERR_InitializedInjectionPoint"));      // NOI18N
        }
    }
    Set<Modifier> modifiers = element.getModifiers();
    if ( modifiers.contains(Modifier.STATIC)){
        throw new InjectionPointDefinitionError(NbBundle.getMessage( 
                FieldInjectionPointLogic.class, 
                "ERR_StaticInjectionPoint"));      // NOI18N
    }
    if ( modifiers.contains(Modifier.FINAL)){
        throw new InjectionPointDefinitionError(NbBundle.getMessage( 
                FieldInjectionPointLogic.class, 
                "ERR_FinalInjectionPoint"));      // NOI18N
    }
}
 
Example 13
Source File: ProducerFieldAnalyzer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void checkSessionBean( VariableElement element, TypeElement parent,
        CdiAnalysisResult result  )
{
    if ( !AnnotationUtil.isSessionBean( parent , result.getInfo())) {
        return;
    }
    Set<Modifier> modifiers = element.getModifiers();
    if ( !modifiers.contains(Modifier.STATIC)){
        result.addError( element,  NbBundle.getMessage(
                ProducerFieldAnalyzer.class, 
                "ERR_NonStaticProducerSessionBean"));    // NOI18N
    }
}
 
Example 14
Source File: EntityClassInfo.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean useFieldAccess(TypeElement typeElement, 
        CompilationController controller) 
{
    List<VariableElement> fields = ElementFilter.fieldsIn(typeElement.getEnclosedElements());

    for (VariableElement field : fields) {
        Set<Modifier> modifiers = field.getModifiers();
        if (modifiers.contains(Modifier.STATIC) || modifiers.contains(Modifier.TRANSIENT) || modifiers.contains(Modifier.VOLATILE) || modifiers.contains(Modifier.FINAL)) {
            continue;
        }

        FieldInfo fieldInfo = new FieldInfo();

        fieldInfo.parseAnnotations(field.getAnnotationMirrors());

        if (fieldInfo.isPersistent() && fieldInfo.hasPersistenceAnnotation()) {
            return true;
        }
    }
    
    TypeElement superClass = getJPASuperClass(typeElement, controller);
    if ( superClass != null ){
            return useFieldAccess(superClass, controller);
    }

    return false;
}
 
Example 15
Source File: ProcessUtils.java    From Freezer with Apache License 2.0 5 votes vote down vote up
public static List<VariableElement> filterStaticFinal(List<VariableElement> elements) {
    List<VariableElement> filtered = new ArrayList<>();
    for (VariableElement variableElement : elements) {
        final Set<Modifier> modifiers = variableElement.getModifiers();
        if (!modifiers.containsAll(Arrays.asList(Modifier.FINAL, Modifier.STATIC))) {
            filtered.add(variableElement);
        }
    } return filtered;
}
 
Example 16
Source File: EntityClassInfo.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected void extractFields(DeclaredType originalEntity, TypeElement typeElement, 
        CompilationController controller) 
{
    List<VariableElement> fields = ElementFilter.fieldsIn(typeElement.getEnclosedElements());

    for (VariableElement field : fields) {
        Set<Modifier> modifiers = field.getModifiers();
        if (modifiers.contains(Modifier.STATIC) || modifiers.contains(Modifier.TRANSIENT) || modifiers.contains(Modifier.VOLATILE) || modifiers.contains(Modifier.FINAL)) {
            continue;
        }

        FieldInfo fieldInfo = new FieldInfo();

        fieldInfo.parseAnnotations(field.getAnnotationMirrors());

        if (!fieldInfo.isPersistent()) {
            continue;
        }

        fieldInfos.add(fieldInfo);
        fieldInfo.setName(field.getSimpleName().toString());
        fieldInfo.setType(controller.getTypes().
                asMemberOf(originalEntity, field), controller);

        if (fieldInfo.isId() && idFieldInfo == null ) {
            idFieldInfo = fieldInfo;
        }
    }
    TypeElement superClass = getJPASuperClass(typeElement, controller);
    if ( superClass == null ){
        return;
    }
    extractFields(originalEntity , superClass , controller );
}
 
Example 17
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 18
Source File: PaperParcelDescriptor.java    From paperparcel with Apache License 2.0 4 votes vote down vote up
private static boolean isReadableDirectly(VariableElement field) {
  Set<Modifier> fieldModifiers = field.getModifiers();
  return !fieldModifiers.contains(Modifier.PRIVATE);
}
 
Example 19
Source File: PropertyProcessor.java    From jasperreports with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv)
{
	CompiledPropertiesMetadata props = new CompiledPropertiesMetadata();
	String messagesName = processingEnv.getOptions().get(OPTION_MESSAGES_NAME);
	props.setMessagesName(messagesName);
	
	for (TypeElement annotation : annotations)
	{
		Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(annotation);
		for (Element element : elements)
		{
			if (element.getKind() != ElementKind.FIELD)
			{
				processingEnv.getMessager().printMessage(Kind.WARNING, 
						"Annotation " + annotation + " can only be applied to static fields", 
						element);
				continue;
			}
			
			VariableElement varElement = (VariableElement) element;
			Set<Modifier> modifiers = varElement.getModifiers();
			if (!modifiers.contains(Modifier.STATIC) || !modifiers.contains(Modifier.PUBLIC)
					|| !modifiers.contains(Modifier.FINAL))
			{
				processingEnv.getMessager().printMessage(Kind.WARNING, 
						"Annotation " + annotation + " can only be applied to public static final fields", 
						element);
				continue;
			}
			
			TypeMirror varType = varElement.asType();
			if (!varType.toString().equals(String.class.getCanonicalName()))
			{
				processingEnv.getMessager().printMessage(Kind.WARNING, 
						"Annotation " + annotation + " can only be applied to String fields", 
						element);
				continue;
			}
			
			AnnotationMirror propertyAnnotation = findPropertyAnnotation(varElement);
			if (propertyAnnotation == null)
			{
				//should not happen
				continue;
			}
			
			CompiledPropertyMetadata property = toPropertyMetadata(varElement, propertyAnnotation);
			if (property != null)
			{
				props.addProperty(property);
			}
		}
	}
	
	if (!props.getProperties().isEmpty())
	{
		writePropertiesMetadata(props);
		
		String propertiesDoc = processingEnv.getOptions().get(OPTION_PROPERTIES_DOC);
		if (propertiesDoc != null)
		{
			PropertiesDocReader docReader = new PropertiesDocReader(processingEnv, props);
			docReader.readPropertiesDoc(propertiesDoc);
			docReader.writeDefaultMessages();
			
			String referenceOut = processingEnv.getOptions().get(OPTION_CONFIG_REFERENCE_OUT);
			if (referenceOut != null)
			{
				docReader.writeConfigReference(referenceOut);
			}
		}
	}
	
	return true;
}
 
Example 20
Source File: PaperParcelDescriptor.java    From paperparcel with Apache License 2.0 4 votes vote down vote up
private static boolean isWritableDirectly(VariableElement field) {
  Set<Modifier> fieldModifiers = field.getModifiers();
  return !fieldModifiers.contains(Modifier.PRIVATE)
      && !fieldModifiers.contains(Modifier.FINAL);
}