Java Code Examples for javax.lang.model.element.ElementKind.ENUM_CONSTANT

The following are Jave code examples for showing how to use ENUM_CONSTANT of the javax.lang.model.element.ElementKind class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: GitHub   File: OkJsons.java   View Source Code Vote up 6 votes
EnumDefinition(TypeElement element, String qualified, String simple) {
  this.qualified = qualified;
  this.simple = simple;

  for (Element e : element.getEnclosedElements()) {
    if (e.getKind() == ElementKind.ENUM_CONSTANT) {
      Optional<OkNamedMirror> nameAnnotation = OkNamedMirror.find(e);
      String name = e.getSimpleName().toString();
      String jsonName = name;

      if (nameAnnotation.isPresent()) {
        String s = nameAnnotation.get().name();
        // just ignore annotation with empty name
        if (!s.isEmpty()) {
          jsonName = s;
        }
      }
      byFirstLetter.put(
          jsonName.charAt(0),
          new EnumConstant(name, jsonName));
    }
  }
}
 
Example 2
Project: incubator-netbeans   File: TranslateIdentifier.java   View Source Code Vote up 6 votes
public Void visitIdentifier(IdentifierTree node, Void p) {
    TreePath path = getCurrentPath();
    Element element = info.getTrees().getElement(path);
    
    if (element != null && element.asType().getKind() != TypeKind.ERROR) {
        // solve the imports only when declared type!!!
        if (element.getKind().isClass() || element.getKind().isInterface()
                || (element.getKind().isField() && ((Symbol) element).isStatic())) {
            Tree parent = path.getParentPath() != null ? path.getParentPath().getLeaf() : null;
            
            if (   (parent != null && parent.getKind() == Kind.CASE && ((CaseTree) parent).getExpression() == node && element.getKind() == ElementKind.ENUM_CONSTANT)
                || (path.getCompilationUnit() != null && ((Symbol) element).enclClass() != null && path.getCompilationUnit().getSourceFile() == ((Symbol) element).enclClass().sourcefile)) {
                translateMap.put(node, make.Identifier(element.getSimpleName()));
            } else {
                translateMap.put(node, make.QualIdent(element));
            }
        } 
    }
    
    return null;
}
 
Example 3
Project: incubator-netbeans   File: ElementScanningTask.java   View Source Code Vote up 6 votes
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 4
Project: incubator-netbeans   File: NPECheck.java   View Source Code Vote up 6 votes
@Override
public State visitMemberSelect(MemberSelectTree node, Void p) {
    State expr = scan(node.getExpression(), p);
    boolean wasNPE = false;
    
    if (expr == State.NULL || expr == State.NULL_HYPOTHETICAL || expr == State.POSSIBLE_NULL || expr == State.POSSIBLE_NULL_REPORT) {
        wasNPE = true;
    }
    
    Element site = info.getTrees().getElement(new TreePath(getCurrentPath(), node.getExpression()));
    
    if (isVariableElement(site) && wasNPE && (variable2State.get((VariableElement) site) == null || !variable2State.get((VariableElement) site).isNotNull())) {
        variable2State.put((VariableElement) site, NOT_NULL_BE_NPE);
    }
    // special case: if the memberSelect selects enum field = constant, it is never null.
    if (site != null && site.getKind() == ElementKind.ENUM) {
        Element enumConst = info.getTrees().getElement(getCurrentPath());
        if (enumConst != null && enumConst.getKind() == ElementKind.ENUM_CONSTANT) {
            return State.NOT_NULL;
        }
    }
    
    return getStateFromAnnotations(info, info.getTrees().getElement(getCurrentPath()));
}
 
Example 5
Project: incubator-netbeans   File: NPECheck.java   View Source Code Vote up 6 votes
@Override
public State visitIdentifier(IdentifierTree node, Void p) {
    super.visitIdentifier(node, p);
    
    Element e = info.getTrees().getElement(getCurrentPath());

    if (e == null || !isVariableElement(e)) {
        return State.POSSIBLE_NULL;
    }
    if (e.getKind() == ElementKind.ENUM_CONSTANT) {
        // enum constants are never null
        return State.NOT_NULL;
    }

    State s = variable2State.get((VariableElement) e);
    if (s != null) {
        return s;
    }
    
    return getStateFromAnnotations(info, e);
}
 
Example 6
Project: incubator-netbeans   File: ImplementAllAbstractMethods.java   View Source Code Vote up 6 votes
protected boolean generateClassBody(TreePath p) throws Exception {
    Element e = copy.getTrees().getElement(p);
    boolean isUsableElement = e != null && (e.getKind().isClass() || e.getKind().isInterface());
    if (isUsableElement) {
        return true;
    }
    if (e.getKind() == ElementKind.ENUM_CONSTANT) {
        VariableTree var = (VariableTree) p.getLeaf();
        if (var.getInitializer() != null && var.getInitializer().getKind() == Kind.NEW_CLASS) {
            NewClassTree nct = (NewClassTree) var.getInitializer();
            if (nct.getClassBody() != null) {
                return true;
            }
        }
    }
    return !generateClassBody2(copy, p);
}
 
Example 7
Project: openjdk-jdk10   File: Symbol.java   View Source Code Vote up 6 votes
@DefinedBy(Api.LANGUAGE_MODEL)
public ElementKind getKind() {
    long flags = flags();
    if ((flags & PARAMETER) != 0) {
        if (isExceptionParameter())
            return ElementKind.EXCEPTION_PARAMETER;
        else
            return ElementKind.PARAMETER;
    } else if ((flags & ENUM) != 0) {
        return ElementKind.ENUM_CONSTANT;
    } else if (owner.kind == TYP || owner.kind == ERR) {
        return ElementKind.FIELD;
    } else if (isResourceVariable()) {
        return ElementKind.RESOURCE_VARIABLE;
    } else {
        return ElementKind.LOCAL_VARIABLE;
    }
}
 
Example 8
Project: easy-plugins   File: Util.java   View Source Code Vote up 6 votes
/**
 * Checks that {@code target} is visible from {@code fromPkg}.
 * If {@code fromPkg} is {@code null}, we take that to mean that {@code target} should be visible everywhere.
 * Throws an {@link EasyPluginException} with a proper error message if the target element does not match
 * the visibility constraint.
 * @param eles Elements
 * @param target The target element to check for visibility
 * @param fromPkg The package to check for visibility from.
 *                Null indicates it needs to be globally visible.
 * @throws EasyPluginException if it's not visible
 */
static void checkElementVisibility(Elements eles, Element target, String fromPkg) {
    // I would have used a switch, but that messed up compilation somehow.
    // I guess it generated another class file?
    // Anyways, this works.
    if (target.getKind().isClass() || target.getKind().isInterface()) {
        checkClassVisibility(eles, (TypeElement) target, fromPkg);
    } else if (target.getKind().isField()
            || target.getKind() == ElementKind.METHOD
            || target.getKind() == ElementKind.CONSTRUCTOR) {
        checkMemberVisibility(eles, target, fromPkg);
    } else if (target.getKind() == ElementKind.ENUM_CONSTANT) {
        checkClassVisibility(eles, (TypeElement) target.getEnclosingElement(), fromPkg);
    } else {
        // This isn't an EasyPluginException because our code shouldn't be dumb
        // enough to check the visibility of any other kind of element.
        throw new IllegalArgumentException("Bad kind for element visibility check: " + target.getKind());
    }
}
 
Example 9
Project: GitHub   File: SwitcherModel.java   View Source Code Vote up 5 votes
private ImmutableList<SwitchOption> constructOptions() {
  ImmutableList.Builder<SwitchOption> builder = ImmutableList.builder();

  for (Element v : containedTypeElement.getEnclosedElements()) {
    if (v.getKind() == ElementKind.ENUM_CONSTANT) {
      String name = v.getSimpleName().toString();
      builder.add(new SwitchOption(name, defaultName.equals(name)));
    }
  }

  return builder.build();
}
 
Example 10
Project: incubator-netbeans   File: Type.java   View Source Code Vote up 5 votes
@Override
public String[] getEnumConstants() {
    if(enumConstants == null){
        Element elt = po != null ? getTypeElement(po) : element;
        if(elt != null){
            ArrayList<String> constants = new ArrayList<String>();
            for( Element el:elt.getEnclosedElements() ){
                if(el.getKind() == ElementKind.ENUM_CONSTANT){
                    constants.add(el.getSimpleName().toString());
                }
            }
            enumConstants = constants.toArray(new String[]{});
        } else if (type != null) {
            if (!type.isEnum()) {
                enumConstants = new String[]{};
            } else {
                Object[] enumC = type.getEnumConstants();
                enumConstants = new String[enumC.length];

                for (int index = enumC.length; --index >= 0;) {
                    enumConstants[index] = ((Enum<?>) enumC[index]).name();
                }

            }
        } else {
            enumConstants = new String[]{};
        }
    }
    return enumConstants;
}
 
Example 11
Project: incubator-netbeans   File: EnumValueCompleter.java   View Source Code Vote up 5 votes
@Override
public List<CompletionItem> complete() {
    List<String> valueStrings = new ArrayList<String>();
    if (isBooleanType()) {
        valueStrings.add(Boolean.FALSE.toString());
        valueStrings.add(Boolean.TRUE.toString());
    } else {
        for (Element e : enumType.getEnclosedElements()) {
            if (e.getKind() == ElementKind.ENUM_CONSTANT) {
                valueStrings.add(e.getSimpleName().toString());
            }
        }
    }
    
    String prefix = ctx.getPrefix();
    if (!prefix.isEmpty()) {
        if (prefix.charAt(0) == '"' || prefix.charAt(0) == '\'') {
            prefix = prefix.substring(1);
        }
        for (Iterator<String> it = valueStrings.iterator(); it.hasNext(); ) {
            String s = it.next();
            if (!CompletionUtils.startsWith(s, prefix)) {
                it.remove();
            }
        }
    }
    
    List<CompletionItem> items = new ArrayList<CompletionItem>();
    for (String v : valueStrings) {
        ValueItem vi = new ValueItem(ctx, v, ICON_ENUM_VALUE);
        items.add(vi);
    }
    
    return items;
}
 
Example 12
Project: incubator-netbeans   File: Tiny.java   View Source Code Vote up 5 votes
private static boolean tryResolveIdentifier(CompilationInfo info, TreePath place, 
        TypeMirror expectedType, Set<Element> resolved, String ident) {
    SourcePositions[] positions = new SourcePositions[1];
    ExpressionTree et = info.getTreeUtilities().parseExpression(ident, positions);
    TypeMirror unqType = info.getTreeUtilities().attributeTree(et, info.getTrees().getScope(place));
    Element e = info.getTrees().getElement(new TreePath(place, et));
    if (!Utilities.isValidType(unqType) || e == null || 
            (e.getKind() != ElementKind.FIELD && e.getKind() != ElementKind.ENUM_CONSTANT)) {
        return false;
    }
    if (!resolved.add(e)) {
        return false;
    }
    return info.getTypes().isAssignable(unqType, expectedType);
}
 
Example 13
Project: incubator-netbeans   File: ImplementAllAbstractMethods.java   View Source Code Vote up 5 votes
@Override
protected boolean executeRound(Element el, int round) throws Exception {
    if (el.getKind() != ElementKind.ENUM) {
        return false;
    }
    ClassTree ct = (ClassTree)path.getLeaf();
    for (ListIterator<? extends Tree> it = ct.getMembers().listIterator(ct.getMembers().size()); it.hasPrevious(); ) {
        Tree t = it.previous();
        
        if (t.getKind() != Tree.Kind.VARIABLE) {
            continue;
        }
        TreePath p = new TreePath(path, t);
        Element e = copy.getTrees().getElement(p);
        if (e == null || e.getKind() != ElementKind.ENUM_CONSTANT) {
            continue;
        }

        switch (round) {
            case 0:
                if (!generateClassBody(p)) {
                    return false;
                }
                break;
            case 1:
                if (!generateImplementation(el, p)) {
                    return false;
                }
                break;
            default:
                throw new IllegalStateException();
        }
    }
    return true;
}
 
Example 14
Project: incubator-netbeans   File: Utilities.java   View Source Code Vote up 5 votes
@Override
public Boolean visitSwitch(SwitchTree node, Void p) {
    boolean lastCaseExit = false;
    boolean defaultSeen = false;
    Set<Element> enumValues = null;
    
    if (node.getExpression() != null) {
        TypeMirror exprType = info.getTrees().getTypeMirror(new TreePath(getCurrentPath(), node.getExpression()));
        if (isValidType(exprType) && exprType.getKind() == TypeKind.DECLARED) {
            Element el = ((DeclaredType)exprType).asElement();
            enumValues = new HashSet<>();
            for (Element f : el.getEnclosedElements()) {
                if (f.getKind() == ElementKind.ENUM_CONSTANT) {
                    enumValues.add(f);
                }
            }
        }
    }
    for (CaseTree ct : node.getCases()) {
        Boolean res = scan(ct, null);
        if (res == Boolean.FALSE) {
            return res;
        }
        lastCaseExit = res == Boolean.TRUE;
        if (ct.getExpression() == null) {
            defaultSeen = true;
        } else if (enumValues != null ) {
            TreePath casePath = new TreePath(getCurrentPath(), ct);
            Element v = info.getTrees().getElement(new TreePath(
                    casePath, ct.getExpression()));
            if (v != null) {
                enumValues.remove(v);
            }
        }
    }
    if (enumValues != null && enumValues.isEmpty()) {
        defaultSeen = true;
    }
    return lastCaseExit == Boolean.TRUE && defaultSeen;
}
 
Example 15
Project: incubator-netbeans   File: IfToSwitchSupport.java   View Source Code Vote up 5 votes
/**
 * Evaluates the constant. The method should return a constant value, possibly wrapped
 * if the value is primitive. It may return an encapsulated constant, with well-defned
 * equals/hashcode. The value is just compared and {@link #convert}ed. <p/>
 * Returns {@code null} if the path is not a compile-time constant.
 * @param path
 * @return constant value.
 */
protected Object evalConstant(TreePath path) {
    TypeMirror m = ci.getTrees().getTypeMirror(path);
    if (m != null && m.getKind() != TypeKind.DECLARED) {
        return ArithmeticUtilities.compute(ci, path, true, true);
    }
    Element e = ci.getTrees().getElement(path);
    if (e != null && e.getKind() == ElementKind.ENUM_CONSTANT) {
        return new EnumConst(e);
    }
    return null;
}
 
Example 16
Project: incubator-netbeans   File: ElementNode.java   View Source Code Vote up 5 votes
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 17
Project: incubator-netbeans   File: JavaI18nSupport.java   View Source Code Vote up 5 votes
/**
 * Finds the target position within the source class element.
 * In the current implementation, the target position is just below
 * the last static field of the class; if there is no static field
 * in the class, the target position is the top of the class.
 * 
 * @param  classMembers  list of all members of the class
 * @param  fields  list of the fields in the class
 * @return  target position ({@code 0}-based) of the field,
 *          or {@code -1} if the field should be added to the end
 *          of the class
 */
private int findTargetPosition(
        List<? extends javax.lang.model.element.Element> classMembers,
        List<? extends VariableElement> fields) {
    if (fields.isEmpty()) {
        return 0;
    }

    int target = 0;
    boolean skippingStaticFields = false;
    Iterator<? extends javax.lang.model.element.Element> membersIt
            = classMembers.iterator();
    for (int index = 0; membersIt.hasNext(); index++) {
        javax.lang.model.element.Element member = membersIt.next();
        ElementKind kind = member.getKind();
        if (kind.isField()
                && (kind != ElementKind.ENUM_CONSTANT)
                && member.getModifiers().contains(Modifier.STATIC)) {
            /* it is a static field - skip it! */
            skippingStaticFields = true;
        } else if (skippingStaticFields) {
            /* we were skipping all static fields - until now */
            skippingStaticFields = false;
            target = index;
        }
    }

    return !skippingStaticFields ? target : -1;
}
 
Example 18
Project: incubator-netbeans   File: Tiny.java   View Source Code Vote up 4 votes
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.suggestions.Tiny.fillSwitch", description = "#DESC_org.netbeans.modules.java.hints.suggestions.Tiny.fillSwitch", category="suggestions", hintKind=Kind.ACTION, severity=Severity.HINT, customizerProvider=CustomizerProviderImpl.class)
@TriggerPattern(value="switch ($expression) { case $cases$; }",
                [email protected](variable="$expression", type="java.lang.Enum"))
public static ErrorDescription fillSwitch(HintContext ctx) {
    int caret = ctx.getCaretLocation();
    SwitchTree st = (SwitchTree) ctx.getPath().getLeaf();
    int switchStart = (int) ctx.getInfo().getTrees().getSourcePositions().getStartPosition(ctx.getPath().getCompilationUnit(), st);
    LineMap lm = ctx.getPath().getCompilationUnit().getLineMap();

    if (lm.getLineNumber(caret) != lm.getLineNumber(switchStart)) return null;
    
    TreePath expression = ctx.getVariables().get("$expression");
    Element possibleEnumElement = ctx.getInfo().getTypes().asElement(ctx.getInfo().getTrees().getTypeMirror(expression));
    
    if (possibleEnumElement == null || !possibleEnumElement.getKind().isClass()) return null;
    
    TypeElement enumType = (TypeElement) possibleEnumElement;
    List<VariableElement> enumConstants = new ArrayList<VariableElement>(enumType.getEnclosedElements().size());
    for (Element e : enumType.getEnclosedElements()) {
        if (e.getKind() == ElementKind.ENUM_CONSTANT) {
            enumConstants.add((VariableElement) e);
        }
    }
    boolean hasDefault = false;
    for (TreePath casePath : ctx.getMultiVariables().get("$cases$")) {
        CaseTree ct = (CaseTree) casePath.getLeaf();

        if (ct.getExpression() == null) {
            hasDefault = true;
        } else {
            enumConstants.remove(ctx.getInfo().getTrees().getElement(new TreePath(casePath, ct.getExpression())));
        }
    }
    boolean generateDefault = ctx.getPreferences().getBoolean(KEY_DEFAULT_ENABLED, DEF_DEFAULT_ENABLED);
    if (enumConstants.isEmpty() && (hasDefault || !generateDefault)) return null;
    List<String> names = new ArrayList<String>(enumConstants.size());
    for (VariableElement constant : enumConstants) {
        names.add(constant.getSimpleName().toString());
    }
    String defaultTemplate = generateDefault ? ctx.getPreferences().get(KEY_DEFAULT_SNIPPET, DEF_DEFAULT_SNIPPET) : null;
    String errMessage = enumConstants.isEmpty() ? "ERR_Tiny.fillSwitchDefault" : !hasDefault && generateDefault ? "ERR_Tiny.fillSwitchCasesAndDefault" : "ERR_Tiny.fillSwitchCases";
    String fixMessage = enumConstants.isEmpty() ? "FIX_Tiny.fillSwitchDefault" : !hasDefault && generateDefault ? "FIX_Tiny.fillSwitchCasesAndDefault" : "FIX_Tiny.fillSwitchCases";
    return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), NbBundle.getMessage(Tiny.class, errMessage), new AddSwitchCasesImpl(ctx.getInfo(), ctx.getPath(), fixMessage, names, defaultTemplate).toEditorFix());
}