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

The following examples show how to use javax.lang.model.element.Element#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: Visitor.java    From helidon-build-tools with Apache License 2.0 6 votes vote down vote up
@Override
public CommandFragmentMetaModel visitType(TypeElement type, Void p) {
    List<MetaModel<?>> params = null;
    for (Element elt : type.getEnclosedElements()) {
        if (elt.getKind() == ElementKind.CONSTRUCTOR && elt.getAnnotation(Creator.class) != null) {
            params = elt.accept(new ConstructorVisitor(), null);
            break;
        }
    }
    if (params != null) {
        String pkg = env.getElementUtils().getPackageOf(type).getQualifiedName().toString();
        CommandFragmentMetaModel model = new CommandFragmentMetaModel(type, pkg, params);
        fragmentsByQualifiedName.put(type.getQualifiedName().toString(), model);
        return model;
    }
    env.getMessager().printMessage(Diagnostic.Kind.ERROR,
                String.format("No constructor annotated with @%s found", Creator.class.getSimpleName()),
                type);
    return null;
}
 
Example 2
Source File: APIIsSelfContainedTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void verifySelfContainedAPI(Element e, TypeElement in) {
    switch (e.getKind()) {
        case ANNOTATION_TYPE:
        case CLASS:
        case INTERFACE:
        case ENUM:
            verifySelfContainedAPI((TypeElement) e);
            break;
        case CONSTRUCTOR:
        case METHOD:
            verifySelfContainedAPI((ExecutableElement) e, in);
            break;
        case FIELD:
            verifySelfContainedAPI((VariableElement) e, in);
            break;
        case PACKAGE:
            verifySelfContainedAPI((PackageElement) e);
            break;
    }
}
 
Example 3
Source File: Tiny.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Hint(displayName = "#DN_CanBeFinal", description = "#DESC_CanBeFinal", category="thread", suppressWarnings="FieldMayBeFinal")
@TriggerTreeKind(Kind.VARIABLE)
public static ErrorDescription canBeFinal(HintContext ctx) {
    Element ve = ctx.getInfo().getTrees().getElement(ctx.getPath());
    
    if (ve == null || ve.getKind() != ElementKind.FIELD || ve.getModifiers().contains(Modifier.FINAL) || /*TODO: the point of volatile?*/ve.getModifiers().contains(Modifier.VOLATILE)) return null;
    
    //we can't say much currently about non-private fields:
    if (!ve.getModifiers().contains(Modifier.PRIVATE)) return null;
    
    FlowResult flow = Flow.assignmentsForUse(ctx);
    
    if (flow == null || ctx.isCanceled()) return null;
    
    if (flow.getFinalCandidates().contains(ve)) {
        VariableTree vt = (VariableTree) ctx.getPath().getLeaf();
        Fix fix = null;
        if (flow.getFieldInitConstructors(ve).size() <= 1) {
            fix = FixFactory.addModifiersFix(ctx.getInfo(), new TreePath(ctx.getPath(), vt.getModifiers()), EnumSet.of(Modifier.FINAL), Bundle.FIX_CanBeFinal(ve.getSimpleName().toString()));
        }
        return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_CanBeFinal(ve.getSimpleName().toString()), fix);
    }
    
    return null;
}
 
Example 4
Source File: ParcelableField.java    From ParcelablePlease with Apache License 2.0 6 votes vote down vote up
/**
 * Checks if an public empty constructor is available
 */
private boolean hasPublicEmptyConstructor(DeclaredType type) {
  Element element = type.asElement();

  List<? extends Element> containing = element.getEnclosedElements();

  for (Element e : containing) {
    if (e.getKind() == ElementKind.CONSTRUCTOR) {
      ExecutableElement c = (ExecutableElement) e;

      if ((c.getParameters() == null || c.getParameters().isEmpty()) && c.getModifiers()
          .contains(javax.lang.model.element.Modifier.PUBLIC)) {
        return true;
      }
    }
  }

  return false;
}
 
Example 5
Source File: InfoTaglet.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public String toString(List<? extends DocTree> tags, Element element) {
    // The content lines below are primarily to help verify the element
    // and the values passed to init.
    return "<dt>"
            +"<span class=\"simpleTagLabel\">Info:</span>\n"
            + "</dt>"
            + "<dd>"
            + "<ul>\n"
            + "<li>Element: " + element.getKind() + " " + element.getSimpleName() + "\n"
            + "<li>Element supertypes: " +
                    env.getTypeUtils().directSupertypes(element.asType()) + "\n"
            + "<li>Doclet: " + doclet.getClass() + "\n"
            + "</ul>\n"
            + "</dd>";
}
 
Example 6
Source File: WorkingRangesMethodExtractor.java    From litho with Apache License 2.0 5 votes vote down vote up
@Nullable
public static SpecMethodModel<EventMethod, Void> getRegisterMethod(
    TypeElement typeElement,
    List<Class<? extends Annotation>> permittedInterStageInputAnnotations,
    Messager messager) {
  for (Element enclosedElement : typeElement.getEnclosedElements()) {
    if (enclosedElement.getKind() != ElementKind.METHOD) {
      continue;
    }

    final ExecutableElement executableElement = (ExecutableElement) enclosedElement;
    final Annotation registerRangesAnnotation =
        enclosedElement.getAnnotation(OnRegisterRanges.class);

    if (registerRangesAnnotation != null) {
      final List<MethodParamModel> methodParams =
          getMethodParams(
              executableElement,
              messager,
              getPermittedMethodParamAnnotations(permittedInterStageInputAnnotations),
              permittedInterStageInputAnnotations,
              ImmutableList.of());

      return SpecMethodModel.<EventMethod, Void>builder()
          .annotations(ImmutableList.of())
          .modifiers(ImmutableList.copyOf(new ArrayList<>(executableElement.getModifiers())))
          .name(executableElement.getSimpleName())
          .returnTypeSpec(generateTypeSpec(executableElement.getReturnType()))
          .typeVariables(ImmutableList.copyOf(getTypeVariables(executableElement)))
          .methodParams(ImmutableList.copyOf(methodParams))
          .representedObject(executableElement)
          .build();
    }
  }
  return null;
}
 
Example 7
Source File: ElementUtils.java    From ngAndroid with Apache License 2.0 5 votes vote down vote up
public boolean isGetterForField(Element elem, String field, TypeKind typeKind){
    return elem != null && ExecutableElement.class.isInstance(elem)
            && elem.getKind() == ElementKind.METHOD
            && elem.getSimpleName().toString().toLowerCase().equals("get" + field.toLowerCase())
            && ((ExecutableElement) elem).getReturnType().getKind() == typeKind
            && ((ExecutableElement) elem).getParameters().size() == 0;
}
 
Example 8
Source File: BindM2MBuilder.java    From kripton with Apache License 2.0 5 votes vote down vote up
public static TypeName findPrimaryKeyFieldType(String entityFullName) {
	TypeElement element = BaseProcessor.elementUtils.getTypeElement(entityFullName);
	List<? extends Element> list = BaseProcessor.elementUtils.getAllMembers(element);
	// fill property map from current class
	Element idField = null;
	String enumValue;
	for (Element item : list) {
		if (item.getKind() == ElementKind.FIELD) {
			enumValue = AnnotationUtility.extractAsEnumerationValue(item, BindSqlColumn.class,
					AnnotationAttributeType.COLUMN_TYPE);
			if (StringUtils.hasText(enumValue) && (ColumnType.valueOf(enumValue) == ColumnType.PRIMARY_KEY
					|| ColumnType.valueOf(enumValue) == ColumnType.PRIMARY_KEY_UNMANGED)) {
				return TypeUtility.typeName(item);
			} else if (item.getSimpleName().toString().equals("id")) {
				idField = item;
			}
		}
	}
	if (idField != null) {
		return TypeUtility.typeName(idField.asType());
	}

	// go up in class hierarchy and extract other fields
	String parentClassName = element.getSuperclass().toString();
	if (parentClassName != null && !Object.class.getCanonicalName().equals(parentClassName)) {
		TypeElement parentTypeElement = BaseProcessor.elementUtils.getTypeElement(parentClassName);
		if (parentTypeElement != null) {
			return findPrimaryKeyFieldType(parentClassName);
		}
	}

	return null;
}
 
Example 9
Source File: SemanticHighlighterBase.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void addParameterInlineHint(Tree tree) {
    TreePath pp = getCurrentPath().getParentPath();
    Tree leaf = pp.getLeaf();
    if (leaf != null &&
        (leaf.getKind() == Kind.METHOD_INVOCATION || leaf.getKind() == Kind.NEW_CLASS)) {
        int pos = -1;
        if (leaf.getKind() == Kind.METHOD_INVOCATION) {
            pos = MethodInvocationTree.class.cast(leaf).getArguments().indexOf(tree);
        } else if (leaf.getKind() == Kind.NEW_CLASS) {
            pos = NewClassTree.class.cast(leaf).getArguments().indexOf(tree);
        }
        if (pos != (-1)) {
            Element invoked = info.getTrees().getElement(pp);
            if (invoked != null && (invoked.getKind() == ElementKind.METHOD || invoked.getKind() == ElementKind.CONSTRUCTOR)) {
                long start = sourcePositions.getStartPosition(info.getCompilationUnit(), tree);
                long end = start + 1;
                ExecutableElement invokedMethod = (ExecutableElement) invoked;
                pos = Math.min(pos, invokedMethod.getParameters().size() - 1);
                if (pos != (-1)) {
                    boolean shouldBeAdded = true;
                    if (tree.getKind() == Kind.IDENTIFIER &&
                            invokedMethod.getParameters().get(pos).getSimpleName().equals(
                                    IdentifierTree.class.cast(tree).getName())) {
                        shouldBeAdded = false;
                    }
                    if (shouldBeAdded) {
                        preText.put(new int[] {(int) start, (int) end},
                                    invokedMethod.getParameters().get(pos).getSimpleName() + ":");
                    }
                }
            }
        }
    }
}
 
Example 10
Source File: PluginGenerator.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static Element getTopLevelClass(Element element) {
    Element prev = element;
    Element enclosing = element.getEnclosingElement();
    while (enclosing != null && enclosing.getKind() != ElementKind.PACKAGE) {
        prev = enclosing;
        enclosing = enclosing.getEnclosingElement();
    }
    return prev;
}
 
Example 11
Source File: TypeAdapterHelper.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * Detect source type.
 *
 * @param element the element
 * @param adapterClazz the adapter clazz
 * @return the string
 */
public static String detectSourceType(Element element, String adapterClazz) {
	TypeElement a = BaseProcessor.elementUtils.getTypeElement(adapterClazz);
	for (Element i : BaseProcessor.elementUtils.getAllMembers(a)) {
		if (i.getKind() == ElementKind.METHOD && "toJava".equals(i.getSimpleName().toString())) {
			ExecutableElement method = (ExecutableElement) i;
			return TypeUtility.typeName(method.getReturnType()).toString();
		}
	}

	AssertKripton.fail("In '%s', class '%s' can not be used as type adapter", element, adapterClazz);
	return null;
}
 
Example 12
Source File: TestRoundEnvironment.java    From RADL with Apache License 2.0 5 votes vote down vote up
public void annotateElement(Element element, TypeElement annotation) {
  elementsByAnnotation.put(annotation, element);
  if (element.getKind() == ElementKind.CLASS) {
    addRootElement(element);
  } else if (element instanceof ExecutableElement) {
    addReturnTypeAsRootElement(element);
  }
}
 
Example 13
Source File: StringBufferCharConstructor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@TriggerPatterns({
    @TriggerPattern(value = "new java.lang.StringBuffer($x)", constraints = @ConstraintVariableType(variable = "$x", type = "char")),
    @TriggerPattern(value = "new java.lang.StringBuilder($x)", constraints = @ConstraintVariableType(variable = "$x", type = "char"))
})
public static ErrorDescription run(HintContext ctx) {
    TreePath p = ctx.getPath();
    
    TypeMirror paramType = ctx.getInfo().getTrees().getTypeMirror(ctx.getVariables().get("$x")); // NOI18N
    if (paramType.getKind() != TypeKind.CHAR) {
        if (paramType.getKind() != TypeKind.DECLARED) {
            return null;
        }
        Element el = ((DeclaredType)paramType).asElement();
        if (el == null || el.getKind() != ElementKind.CLASS) {
            return null;
        }
        if (!((TypeElement)el).getQualifiedName().contentEquals("java.lang.Character")) {
            return null;
        }
    }
    
    TypeMirror tm = ctx.getInfo().getTrees().getTypeMirror(p);
    CharSequence tname = ctx.getInfo().getTypeUtilities().getTypeName(tm);
    
    return ErrorDescriptionFactory.forTree(ctx, p, Bundle.TEXT_StringBufferCharConstructor(tname), 
            new NewAndAppendFix(TreePathHandle.create(p, ctx.getInfo()), tname.toString()).toEditorFix());
}
 
Example 14
Source File: SourceNames.java    From immutables with Apache License 2.0 5 votes vote down vote up
static Element collectClassSegments(Element start, List<String> classSegments) {
  Element e = start;
  for (; e.getKind() != ElementKind.PACKAGE; e = e.getEnclosingElement()) {
    classSegments.add(e.getSimpleName().toString());
  }
  Collections.reverse(classSegments);
  return e;
}
 
Example 15
Source File: ImplementAllAbstractMethods.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@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 16
Source File: BindingDetector.java    From AutoBundle with Apache License 2.0 5 votes vote down vote up
private static String findGetterMethod(Element classElement,
                               VariableElement fieldElement,
                               AutoBundleField fieldAnnotation) {
    final String operation = "get";
    final String argKeyName = fieldAnnotation.key().length() > 0
            ? fieldAnnotation.key() : fieldElement.toString();
    for (Element element : classElement.getEnclosedElements()) {
        final String methodName = element.getSimpleName().toString();
        AutoBundleGetter annotation = element.getAnnotation(AutoBundleGetter.class);
        if (annotation != null) {
            // annotated getter
            if (argKeyName.equals(annotation.key())) {
                // check modifier
                if (element.getModifiers().contains(Modifier.PRIVATE)) {
                    throw new ProcessingException("@AutoBundleGetter must not be private");
                }
                return methodName;
            }
        } else {
            // default getter
            if (ElementKind.METHOD == element.getKind() &&
                    !element.getModifiers().contains(Modifier.PRIVATE) &&
                    element.getSimpleName().toString().startsWith(operation)) {
                if (methodName.equals(
                        createOperationMethod(operation, argKeyName))) {
                    int methodModifierLevel = ModifierHelper.getModifierLevel(element);
                    int fieldModifierLevel = ModifierHelper.getModifierLevel(fieldElement);
                    if (methodModifierLevel - fieldModifierLevel >= 0) {
                        return methodName;
                    }
                }
            }
        }
    }
    return null;
}
 
Example 17
Source File: MIMEResolverProcessor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String getName(Element e) {
    if (e.getKind().isClass() || e.getKind().isInterface()) {
        return processingEnv.getElementUtils().getBinaryName((TypeElement)e).toString();
    } else if (e.getKind() == ElementKind.PACKAGE) {
        return e.getSimpleName().toString();
    } else {
        return getName(e.getEnclosingElement()) + '.' + e.getSimpleName();
    }
}
 
Example 18
Source File: DescriptorFactory.java    From buck with Apache License 2.0 5 votes vote down vote up
@Nullable
public String getDescriptor(Element element) {
  ElementKind kind = element.getKind();
  if (kind.isClass() || kind.isInterface()) {
    return null;
  }
  return getType(element).getDescriptor();
}
 
Example 19
Source File: ElementUtil.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public static boolean isExecutableElement(Element e) {
  ElementKind kind = e.getKind();
  return kind == ElementKind.CONSTRUCTOR || kind == ElementKind.METHOD;
}
 
Example 20
Source File: Tiny.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static ErrorDescription enumHint(HintContext ctx, String baseName, String targetTypeName, String key, Fix... fixes) {
    Element type = ctx.getInfo().getTrees().getElement(ctx.getVariables().get("$param"));

    if (type == null || type.getKind() != ElementKind.ENUM) {
        return null;
    }

    Element coll = ctx.getInfo().getTrees().getElement(ctx.getVariables().get("$coll"));

    if (coll == null || coll.getKind() != ElementKind.CLASS) {
        return null;
    }
    
    TypeElement base = ctx.getInfo().getElements().getTypeElement(baseName);
    
    if (base == null) {
        return null;
    }

    Types t = ctx.getInfo().getTypes();

    if (!t.isSubtype(t.erasure(coll.asType()), t.erasure(base.asType()))) {
        return null;
    }

    if (targetTypeName != null) {
        TypeElement target = ctx.getInfo().getElements().getTypeElement(targetTypeName);

        if (target == null) {
            return null;
        }

        if (t.isSubtype(t.erasure(coll.asType()), t.erasure(target.asType()))) {
            return null;
        }
        
        List<? extends TypeMirror> assignedTo = CreateElementUtilities.resolveType(EnumSet.noneOf(ElementKind.class), ctx.getInfo(), ctx.getPath().getParentPath(), ctx.getPath().getLeaf(), (int) ctx.getInfo().getTrees().getSourcePositions().getEndPosition(ctx.getPath().getCompilationUnit(), ctx.getPath().getLeaf()), new TypeMirror[1], new int[1]);
        
        if (assignedTo != null && assignedTo.size() == 1) {
            if (t.isSubtype(t.erasure(assignedTo.get(0)), t.erasure(coll.asType())))
                return null;
        }
    }

    String displayName = NbBundle.getMessage(Tiny.class, key);

    return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), displayName, fixes);
}