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

The following examples show how to use javax.lang.model.element.VariableElement#getKind() . 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: PrintingProcessor.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
@Override
public PrintingElementVisitor visitVariable(VariableElement e, Boolean newLine) {
    ElementKind kind = e.getKind();
    defaultAction(e, newLine);

    if (kind == ENUM_CONSTANT)
        writer.print(e.getSimpleName());
    else {
        writer.print(e.asType().toString() + " " + e.getSimpleName() );
        Object constantValue  = e.getConstantValue();
        if (constantValue != null) {
            writer.print(" = ");
            writer.print(elementUtils.getConstantExpression(constantValue));
        }
        writer.println(";");
    }
    return this;
}
 
Example 2
Source File: ElementScanningTask.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private String createHtmlHeader(CompilationInfo info, VariableElement e, boolean isDeprecated,boolean isInherited, boolean fqn) {

        StringBuilder sb = new StringBuilder();

        if ( isDeprecated ) {
            sb.append("<s>"); // NOI18N
        }
        if( isInherited ) {
            sb.append( "<font color=" + ui.getInheritedColor() + ">" ); // NOI18N
        }
        sb.append(Utils.escape(e.getSimpleName().toString()));
        if ( isDeprecated ) {
            sb.append("</s>"); // NOI18N
        }

        if ( e.getKind() != ElementKind.ENUM_CONSTANT ) {
            sb.append( " : " ); // NOI18N
            sb.append( "<font color=" + ui.getTypeColor() + ">" ); // NOI18N
            sb.append(print(info, e.asType(), fqn));
            sb.append("</font>"); // NOI18N
        }

        return sb.toString();            
    }
 
Example 3
Source File: Utilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
     * Strips the variable name off prefixes and suffixes configured in the coding style. Handles 
     * fields, local variables, parameters and constants.
     * 
     * @param style the code style
     * @param el the variable element 
     * @return name stripped of prefixes/suffices
     */
    public static String stripVariableName(CodeStyle style, VariableElement el) {
        String n = el.getSimpleName().toString();
        switch (el.getKind()) {
            case PARAMETER:
                return stripVariableName(n, style.getParameterNamePrefix(), style.getParameterNameSuffix());
                
            case LOCAL_VARIABLE:
            case RESOURCE_VARIABLE:
            case EXCEPTION_PARAMETER:
                return stripVariableName(n, style.getLocalVarNamePrefix(), style.getLocalVarNameSuffix());
                
            case FIELD: {
//                boolean c = el.getModifiers().containsAll(EnumSet.of(Modifier.FINAL, Modifier.STATIC));
//                if (!c) {
//                    break;
//                }
                // fall through to enum constant
            }
            case ENUM_CONSTANT:
                return stripVariableName(n, style.getFieldNamePrefix(), style.getFieldNameSuffix());
                
            default:
                return n;
        }
    }
 
Example 4
Source File: SwitchRewriter.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Override
public void endVisit(SwitchCase node) {
  Expression expr = node.getExpression();
  VariableElement var = expr != null ? TreeUtil.getVariableElement(expr) : null;
  if (var == null) {
    return;
  }
  TypeMirror type = var.asType();
  if (TypeUtil.isEnum(type)) {
    String enumValue =
        NameTable.getNativeEnumName(nameTable.getFullName(TypeUtil.asTypeElement(type))) + "_"
        + nameTable.getVariableBaseName(var);
    node.setExpression(new NativeExpression(enumValue, typeUtil.getInt()));
  } else if (type.getKind().isPrimitive() && var.getKind() == ElementKind.LOCAL_VARIABLE) {
    Object value = var.getConstantValue();
    if (value != null) {
      node.setExpression(TreeUtil.newLiteral(value, typeUtil));
    }
  }
}
 
Example 5
Source File: JRepeatableCodeGenerator.java    From jackdaw with Apache License 2.0 6 votes vote down vote up
private Pair<String, Object> calculateValue(Object value) {
    String format = "L";
    if (value instanceof CharSequence) {
        format = "S";
    } else if (value instanceof Class) {
        format = "T";
    } else if (value instanceof VariableElement) {
        final VariableElement variableElement = (VariableElement) value;
        final ElementKind kind = variableElement.getKind();
        if (kind == ElementKind.ENUM_CONSTANT) {
            final Element classElement = ((VariableElement) value).getEnclosingElement();
            value = classElement + SourceTextUtils.PACKAGE_SEPARATOR + variableElement;
            format = "L";
        }
    }
    return Pair.of("$" + format, value);
}
 
Example 6
Source File: MetamodelAttribute.java    From spring-data-jpa-entity-graph with MIT License 6 votes vote down vote up
public static Optional<MetamodelAttribute> parse(
    Elements elements, Types types, Element element) {
  if (!(element instanceof VariableElement)) {
    return Optional.empty();
  }

  VariableElement variableElement = (VariableElement) element;
  if (variableElement.getKind() != FIELD) {
    return Optional.empty();
  }

  TypeElement attributeTypeElement = elements.getTypeElement(Attribute.class.getCanonicalName());
  if (!types.isSubtype(
      types.erasure(variableElement.asType()), types.erasure(attributeTypeElement.asType()))) {
    return Optional.empty();
  }

  return Optional.of(new MetamodelAttribute(variableElement));
}
 
Example 7
Source File: ElementKindVisitor6.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Visits a variable element, dispatching to the visit method for
 * the specific {@linkplain ElementKind kind} of variable, {@code
 * ENUM_CONSTANT}, {@code EXCEPTION_PARAMETER}, {@code FIELD},
 * {@code LOCAL_VARIABLE}, {@code PARAMETER}, or {@code RESOURCE_VARIABLE}.
 *
 * @param e {@inheritDoc}
 * @param p {@inheritDoc}
 * @return  the result of the kind-specific visit method
 */
@Override
public R visitVariable(VariableElement e, P p) {
    ElementKind k = e.getKind();
    switch(k) {
    case ENUM_CONSTANT:
        return visitVariableAsEnumConstant(e, p);

    case EXCEPTION_PARAMETER:
        return visitVariableAsExceptionParameter(e, p);

    case FIELD:
        return visitVariableAsField(e, p);

    case LOCAL_VARIABLE:
        return visitVariableAsLocalVariable(e, p);

    case PARAMETER:
        return visitVariableAsParameter(e, p);

    case RESOURCE_VARIABLE:
        return visitVariableAsResourceVariable(e, p);

    default:
        throw new AssertionError("Bad kind " + k + " for VariableElement" + e);
    }
}
 
Example 8
Source File: TreeBackedVariableElement.java    From buck with Apache License 2.0 5 votes vote down vote up
TreeBackedVariableElement(
    VariableElement underlyingElement,
    TreeBackedElement enclosingElement,
    @Nullable TreePath treePath,
    PostEnterCanonicalizer canonicalizer) {
  super(underlyingElement, enclosingElement, treePath, canonicalizer);
  this.underlyingElement = underlyingElement;
  this.tree = treePath == null ? null : (VariableTree) treePath.getLeaf();
  if (underlyingElement.getKind() == ElementKind.PARAMETER) {
    ((TreeBackedExecutableElement) enclosingElement).addParameter(this);
  } else {
    enclosingElement.addEnclosedElement(this);
  }
}
 
Example 9
Source File: AccessFlags.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the field access flags (see JVMS8 4.5) for the given variable element, augmented by the
 * special ASM pseudo-access flag for @Deprecated fields.
 */
public int getAccessFlags(VariableElement variableElement) {
  int result = getCommonAccessFlags(variableElement);

  if (variableElement.getKind() == ElementKind.ENUM_CONSTANT) {
    result = result | Opcodes.ACC_ENUM;
  }

  return result;
}
 
Example 10
Source File: TestGenProcessor.java    From vertx-docgen with Apache License 2.0 5 votes vote down vote up
protected String resolveFieldLink(VariableElement elt, Coordinate coordinate) {
  switch (elt.getKind()) {
    case ENUM_CONSTANT:
      return "enumConstant";
    case FIELD:
      return "field";
    default:
      return "unsupported";
  }
}
 
Example 11
Source File: InterfaceScannerTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public void onConstantReferenceFound(
    VariableElement constant, TreePath path, Element referencingElement) {
  String value;
  if (constant.getKind() == ElementKind.ENUM_CONSTANT) {
    value = constant.getSimpleName().toString();
  } else {
    value = constant.getConstantValue().toString();
  }

  constantReferences.add(createSymbolicReference(value, path));
}
 
Example 12
Source File: ELHyperlinkProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitVariable(VariableElement e, Boolean highlightName) {
    modifier(e.getModifiers());

    result.append(getTypeName(info, e.asType(), true));

    result.append(' ');

    boldStartCheck(highlightName);

    result.append(e.getSimpleName());

    boldStopCheck(highlightName);

    if (highlightName) {
        if (e.getConstantValue() != null) {
            result.append(" = ");
            result.append(e.getConstantValue().toString());
        }

        Element enclosing = e.getEnclosingElement();

        if (e.getKind() != ElementKind.PARAMETER && e.getKind() != ElementKind.LOCAL_VARIABLE && e.getKind() != ElementKind.EXCEPTION_PARAMETER) {
            result.append(" in ");

            //short typename:
            result.append(getTypeName(info, enclosing.asType(), true));
        }
    }

    return null;
}
 
Example 13
Source File: GoToSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitVariable(VariableElement e, Boolean highlightName) {
    modifier(e.getModifiers());
    
    result.append(getTypeName(info, e.asType(), true));
    
    result.append(' ');
    
    boldStartCheck(highlightName);

    result.append(e.getSimpleName());
    
    boldStopCheck(highlightName);
    
    if (highlightName) {
        if (e.getConstantValue() != null) {
            result.append(" = ");
            result.append(StringEscapeUtils.escapeHtml(e.getConstantValue().toString()));
        }
        
        Element enclosing = e.getEnclosingElement();
        
        if (e.getKind() != ElementKind.PARAMETER && e.getKind() != ElementKind.LOCAL_VARIABLE
                && e.getKind() != ElementKind.RESOURCE_VARIABLE && e.getKind() != ElementKind.EXCEPTION_PARAMETER
                && !TreeShims.BINDING_VARIABLE.equals(e.getKind().name())) {
            result.append(" in ");

            //short typename:
            result.append(getTypeName(info, enclosing.asType(), true));
        }
    }
    
    return null;
}
 
Example 14
Source File: ElementNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static String createHtmlHeader(boolean deprecated, VariableElement e) {
    StringBuilder sb = new StringBuilder();
    sb.append("<html>");
    if (deprecated) sb.append("<s>");
    sb.append(e.getSimpleName());
    if (deprecated) sb.append("</s>");
    if ( e.getKind() != ElementKind.ENUM_CONSTANT ) {
        sb.append( " : " ); // NOI18N
        sb.append(translateToHTML(print(e.asType())));
    }
    return sb.toString();
}
 
Example 15
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 16
Source File: Utils.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public int getOrdinalValue(VariableElement member) {
    if (member == null || member.getKind() != ENUM_CONSTANT) {
        throw new IllegalArgumentException("must be an enum constant: " + member);
    }
    return member.getEnclosingElement().getEnclosedElements().indexOf(member);
}
 
Example 17
Source File: ProcessUtils.java    From RxAndroidOrm with Apache License 2.0 4 votes vote down vote up
private static boolean isNotVariable(VariableElement variableElement) {
    return variableElement.getKind() == ElementKind.ENUM ||
            variableElement.getKind() == ElementKind.INTERFACE ||
            variableElement.getKind() == ElementKind.CLASS;
}
 
Example 18
Source File: GeneratedVariableElement.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public static GeneratedVariableElement mutableCopy(VariableElement var) {
  return new GeneratedVariableElement(
      var.getSimpleName().toString(), var.asType(), var.getKind(), var.getEnclosingElement(),
      ElementUtil.isSynthetic(var));
}
 
Example 19
Source File: ElementUtil.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Returns whether this variable will be an ObjC instance variable.
 */
public static boolean isInstanceVar(VariableElement element) {
  return element.getKind() == ElementKind.FIELD && !isGlobalVar(element);
}
 
Example 20
Source File: NoLoggers.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@TriggerTreeKind({Tree.Kind.ANNOTATION_TYPE, Tree.Kind.CLASS, Tree.Kind.ENUM, Tree.Kind.INTERFACE})
public static Iterable<ErrorDescription> checkNoLoggers(HintContext ctx) {
    Element cls = ctx.getInfo().getTrees().getElement(ctx.getPath());
    if (cls == null || cls.getKind() != ElementKind.CLASS || cls.getModifiers().contains(Modifier.ABSTRACT) ||
        (cls.getEnclosingElement() != null && cls.getEnclosingElement().getKind() != ElementKind.PACKAGE)
    ) {
        return null;
    }

    TypeElement loggerTypeElement = ctx.getInfo().getElements().getTypeElement("java.util.logging.Logger"); // NOI18N
    if (loggerTypeElement == null) {
        return null;
    }
    TypeMirror loggerTypeElementAsType = loggerTypeElement.asType();
    if (loggerTypeElementAsType == null || loggerTypeElementAsType.getKind() != TypeKind.DECLARED) {
        return null;
    }

    List<TypeMirror> customLoggersList = new ArrayList<>();
    if (isCustomEnabled(ctx.getPreferences())) {
        List<String> customLoggerClasses = getCustomLoggers(ctx.getPreferences());
        if (customLoggerClasses != null) {
            for (String className : customLoggerClasses) {
                TypeElement customTypeElement = ctx.getInfo().getElements().getTypeElement(className);
                if (customTypeElement == null) {
                    continue;
                }
                TypeMirror customTypeMirror = customTypeElement.asType();
                if (customTypeMirror == null || customTypeMirror.getKind() != TypeKind.DECLARED) {
                    continue;
                }
                customLoggersList.add(customTypeMirror);
            }
        }
    }

    List<VariableElement> loggerFields = new LinkedList<VariableElement>();
    List<VariableElement> fields = ElementFilter.fieldsIn(cls.getEnclosedElements());
    for(VariableElement f : fields) {
        if (f.getKind() != ElementKind.FIELD) {
            continue;
        }

        if (f.asType().equals(loggerTypeElementAsType)) {
            loggerFields.add(f);
        } else if (customLoggersList.contains(f.asType())) {
            loggerFields.add(f);
        }
    }

    if (loggerFields.size() == 0) {
        return Collections.singleton(ErrorDescriptionFactory.forName(
                ctx,
                ctx.getPath(),
                NbBundle.getMessage(NoLoggers.class, "MSG_NoLoggers_checkNoLoggers", cls), //NOI18N
                new NoLoggersFix(NbBundle.getMessage(NoLoggers.class, "MSG_NoLoggers_checkNoLoggers_Fix", cls), TreePathHandle.create(cls, ctx.getInfo())).toEditorFix() //NOI18N
        ));
    } else {
        return null;
    }
}