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

The following examples show how to use javax.lang.model.element.ElementKind. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: immutables   Source File: Constitution.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void lateValidateSuper(TypeElement t) {
  super.lateValidateSuper(t);

  if (t.getKind() == ElementKind.CLASS) {
    String superclassString = SourceExtraction.getSuperclassString(t);
    String rawSuperclass = SourceTypes.extract(superclassString).getKey();
    // We need to extend the base class
    if (!rawSuperclass.equals(typeAbstract().toString())) {
      protoclass()
              .report()
              .withElement(t)
              .error("%s needs to extend the base class",
                      t.getSimpleName());
    }
  }
}
 
Example 2
Source Project: android-transformer   Source File: AnnotationsProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private void processMappableAnnotationElements() {
    for (Element mappableElement : roundEnvironment.getElementsAnnotatedWith(Mappable.class)) {
        if (mappableElement.getKind() == ElementKind.CLASS) {

            AnnotationMirror mappableAnnotationMirror = getAnnotationMirror(mappableElement, Mappable.class);
            AnnotationValue  annotationValue = getAnnotationValue(mappableAnnotationMirror, "with");
            TypeElement linkedElement = getTypeElement(annotationValue);

            ClassInfo mappableClassInfo = extractClassInformation(mappableElement);
            ClassInfo linkedClassInfo = extractClassInformation(linkedElement);

            if (!haveMapper(mappableClassInfo))
                createMapper(mappableElement.asType().toString(), mappableClassInfo, linkedClassInfo);
        }
    }
}
 
Example 3
private boolean validConstructor(Element el) {
	for (Element subelement : el.getEnclosedElements()) {
		if (subelement.getKind() == ElementKind.CONSTRUCTOR) {
			if (!subelement.getModifiers().contains(Modifier.PUBLIC)) {
				processingEnv.getMessager().printMessage(Kind.ERROR,
						"Invalid constructor visibility for plugin " + subelement.toString());
				return false;
			}
			ExecutableType mirror = (ExecutableType) subelement.asType();
			if (!mirror.getParameterTypes().isEmpty()) {
				processingEnv.getMessager().printMessage(Kind.ERROR,
						"Invalid constructor for plugin, taking arguments is not allowed: " + subelement.toString());
				return false;
			}
		}
	}
	return true;
}
 
Example 4
Source Project: netbeans   Source File: ResolvedJavaSymbolDescriptor.java    License: Apache License 2.0 6 votes vote down vote up
ResolvedJavaSymbolDescriptor (
        @NonNull final JavaSymbolDescriptorBase base,
        @NonNull final String simpleName,
        @NullAllowed final String simpleNameSuffix,
        @NullAllowed final String ownerName,
        @NonNull final ElementKind kind,
        @NonNull final Set<Modifier> modifiers,
        @NonNull final ElementHandle<?> me) {
    super(base, ownerName);
    assert simpleName != null;
    assert kind != null;
    assert modifiers != null;
    assert me != null;
    this.simpleName = simpleName;
    this.simpleNameSuffix = simpleNameSuffix;
    this.kind = kind;
    this.modifiers = modifiers;
    this.me = me;
}
 
Example 5
Source Project: Auto-Dagger2   Source File: ComponentProcessing.java    License: MIT License 6 votes vote down vote up
@Override
public boolean processElement(Element element, Errors.ElementErrors elementErrors) {
    if (ElementKind.ANNOTATION_TYPE.equals(element.getKind())) {
        // @AutoComponent is applied on another annotation, find out the targets of that annotation
        Set<? extends Element> targetElements = roundEnvironment.getElementsAnnotatedWith(MoreElements.asType(element));
        for (Element targetElement : targetElements) {
            process(targetElement, element);
            if (errors.hasErrors()) {
                return false;
            }
        }
        return true;
    }

    process(element, element);

    if (errors.hasErrors()) {
        return false;
    }

    return true;
}
 
Example 6
Source Project: picocli   Source File: DynamicProxyConfigGenerator.java    License: Apache License 2.0 6 votes vote down vote up
void visitCommandSpec(CommandSpec spec) {
    Object userObject = spec.userObject();
    if (Proxy.isProxyClass(userObject.getClass())) {
        Class<?>[] interfaces = userObject.getClass().getInterfaces();
        String names = "";
        for (Class<?> interf : interfaces) {
            if (names.length() > 0) { names += ","; }
            names += interf.getCanonicalName(); // TODO or Class.getName()?
        }
        if (names.length() > 0) {
            commandInterfaces.add(names);
        }
    } else if (spec.userObject() instanceof Element && ((Element) spec.userObject()).getKind() == ElementKind.INTERFACE) {
        commandInterfaces.add(((Element) spec.userObject()).asType().toString());
    }
    for (CommandSpec mixin : spec.mixins().values()) {
        visitCommandSpec(mixin);
    }
    for (CommandLine sub : spec.subcommands().values()) {
        visitCommandSpec(sub.getCommandSpec());
    }
}
 
Example 7
public ConvertToLambdaPreconditionChecker(TreePath pathToNewClassTree, CompilationInfo info) {

        this.pathToNewClassTree = pathToNewClassTree;
        this.newClassTree = (NewClassTree) pathToNewClassTree.getLeaf();
        this.info = info;
        this.types = info.getTypes();

        Element el = info.getTrees().getElement(pathToNewClassTree);
        if (el != null && el.getKind() == ElementKind.CONSTRUCTOR) {
            createdClass = el.getEnclosingElement();
        } else {
            createdClass = null;
        }
        this.lambdaMethodTree = getMethodFromFunctionalInterface(this.pathToNewClassTree);
        this.localScope = getScopeFromTree(this.pathToNewClassTree);
        this.ownerClass = findFieldOwner();
    }
 
Example 8
Source Project: hkt   Source File: HktProcessor.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private String expectedHktInterfaceMessage(TypeElement tel, HktConf conf) {
    final String witnessTypeName = Optional.of(_HktConf.getWitnessTypeName(conf)).filter(w -> !w.startsWith(":")).orElse("ยต");

    return format("%s should %s %s", tel.toString(), tel.getKind() == ElementKind.CLASS ? "implements" : "extends",

        Opt.cata(findImplementedHktInterface(tel.asType())
                .flatMap(hktInterface -> hktInterface.getTypeArguments().stream()
                    .findFirst().flatMap(tm -> asValidTCWitness(tel, tm)))

            , tcWitness -> expectedHktInterface(tel, tcWitness.toString())

            , () -> tel.getTypeParameters().size() <= 1

                ? expectedHktInterface(tel, Types.getDeclaredType(tel, tel.getTypeParameters().stream()
                .map(__ -> Types.getWildcardType(null, null))
                .toArray(TypeMirror[]::new)).toString())

                : format("%s with %s being the following nested class of %s:%n    %s"
                , expectedHktInterface(tel, witnessTypeName)
                , witnessTypeName
                , tel.toString()
                , "public enum " + witnessTypeName + " {}")));
}
 
Example 9
Source Project: WandFix   Source File: InjectObjectField.java    License: MIT License 6 votes vote down vote up
public InjectObjectField(Element element) throws IllegalArgumentException {
    if (element.getKind() != ElementKind.FIELD) {
        throw new IllegalArgumentException(String.format("Only fields can be annotated with @%s",
                InjectObject.class.getSimpleName()));
    }
    mVariableElement = (VariableElement) element;

    InjectObject injectOvject = mVariableElement.getAnnotation(InjectObject.class);
    mClassName = injectOvject.className();
    mLevel = injectOvject.level();
    if (mClassName == null) {
        throw new IllegalArgumentException(
                String.format("value() in %s for field %s is not valid !", InjectObject.class.getSimpleName(),
                        mVariableElement.getSimpleName()));
    }
}
 
Example 10
Source Project: netbeans   Source File: EnumValueCompleter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Completer createCompleter(CompletionContext ctx) {
    FxProperty p = ctx.getEnclosingProperty();
    if (p == null || p.getType() == null) {
        return null;
    }
    TypeMirror m = p.getType().resolve(ctx.getCompilationInfo());
    if (m.getKind() == TypeKind.BOOLEAN) {
        return new EnumValueCompleter(ctx);
    }
    if (m.getKind() != TypeKind.DECLARED) {
        return null;
    }
    DeclaredType t = (DeclaredType)m;
    TypeElement tel = (TypeElement)t.asElement();
    if (tel.getQualifiedName().contentEquals("java.lang.Boolean")) {
        return new EnumValueCompleter(ctx);
    }
    if (tel.getKind() == ElementKind.ENUM) {
        return new EnumValueCompleter(ctx, tel);
    } else {
        return null;
    }
}
 
Example 11
Source Project: openjdk-jdk8u   Source File: JavacTrees.java    License: GNU General Public License v2.0 6 votes vote down vote up
private Symbol attributeParamIdentifier(TreePath path, DCParam ptag) {
    Symbol javadocSymbol = getElement(path);
    if (javadocSymbol == null)
        return null;
    ElementKind kind = javadocSymbol.getKind();
    List<? extends Symbol> params = List.nil();
    if (kind == ElementKind.METHOD || kind == ElementKind.CONSTRUCTOR) {
        MethodSymbol ee = (MethodSymbol) javadocSymbol;
        params = ptag.isTypeParameter()
                ? ee.getTypeParameters()
                : ee.getParameters();
    } else if (kind.isClass() || kind.isInterface()) {
        ClassSymbol te = (ClassSymbol) javadocSymbol;
        params = te.getTypeParameters();
    }

    for (Symbol param : params) {
        if (param.getSimpleName() == ptag.getName().getName()) {
            return param;
        }
    }
    return null;
}
 
Example 12
Source Project: picocli   Source File: MixinInfo.java    License: Apache License 2.0 6 votes vote down vote up
public MixinInfo(VariableElement element, CommandSpec mixin) {
    this.element = element;
    this.mixin = mixin;

    String name = element.getAnnotation(CommandLine.Mixin.class).name();
    if (name.length() == 0) {
        name = element.getSimpleName().toString();
    }
    this.mixinName = name;
    Element targetType = element.getEnclosingElement();
    int position = -1;
    if (EnumSet.of(ElementKind.METHOD, ElementKind.CONSTRUCTOR).contains(targetType.getKind())) {
        List<? extends VariableElement> parameters = ((ExecutableElement) targetType).getParameters();
        for (int i = 0; i < parameters.size(); i++) {
            if (parameters.get(i).getSimpleName().contentEquals(element.getSimpleName())) {
                position = i;
                break;
            }
        }
    }
    annotatedElement = new TypedMember(element, position);
}
 
Example 13
Source Project: soabase-halva   Source File: ImplicitValue.java    License: Apache License 2.0 6 votes vote down vote up
private void addDirectValue(CodeBlock.Builder builder)
{
    Element element = foundImplicit.getElement();
    if ( element.getKind() == ElementKind.FIELD )
    {
        builder.add("$T.$L", element.getEnclosingElement().asType(), element.getSimpleName());
    }
    else
    {
        ExecutableElement method = (ExecutableElement)element;
        AtomicBoolean isFirst = new AtomicBoolean(false);
        CodeBlock methodCode = new ImplicitMethod(environment, method, implicitClassSpec, contextItems).build();
        builder.add("$T.$L(", element.getEnclosingElement().asType(), element.getSimpleName());
        builder.add(methodCode);
        builder.add(")");
    }
}
 
Example 14
Source Project: openjdk-jdk9   Source File: ElementsTable.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the module documentation level mode.
 * @return the module documentation level mode
 */
public ModuleMode getModuleMode() {
    switch(accessFilter.getAccessValue(ElementKind.MODULE)) {
        case PACKAGE: case PRIVATE:
            return DocletEnvironment.ModuleMode.ALL;
        default:
            return DocletEnvironment.ModuleMode.API;
    }
}
 
Example 15
Source Project: NullAway   Source File: AccessPathNullnessPropagation.java    License: MIT License 5 votes vote down vote up
@Override
public TransferResult<Nullness, NullnessStore> visitAssignment(
    AssignmentNode node, TransferInput<Nullness, NullnessStore> input) {
  ReadableUpdates updates = new ReadableUpdates();
  Nullness value = values(input).valueOfSubNode(node.getExpression());
  Node target = node.getTarget();

  if (target instanceof LocalVariableNode) {
    updates.set((LocalVariableNode) target, value);
  }

  if (target instanceof ArrayAccessNode) {
    setNonnullIfAnalyzeable(updates, ((ArrayAccessNode) target).getArray());
  }

  if (target instanceof FieldAccessNode) {
    // we don't allow arbitrary access paths to be tracked from assignments
    // here we still require an access of a field of this, or a static field
    FieldAccessNode fieldAccessNode = (FieldAccessNode) target;
    Node receiver = fieldAccessNode.getReceiver();
    if ((receiver instanceof ThisLiteralNode || fieldAccessNode.isStatic())
        && fieldAccessNode.getElement().getKind().equals(ElementKind.FIELD)) {
      updates.set(fieldAccessNode, value);
    }
  }

  return updateRegularStore(value, input, updates);
}
 
Example 16
private TypeElement outermostTypeElement(Element el) {
    while (el.getEnclosingElement().getKind() != ElementKind.PACKAGE) {
        el = el.getEnclosingElement();
    }

    return (TypeElement) el;
}
 
Example 17
private void filterClass(List<Reference> classes, Collection<? extends Element> elements) {
    for (Element element : elements) {
        if (element.getKind().equals(ElementKind.CLASS) || element.getKind().equals(ElementKind.ENUM)) {
            classes.add(new Reference((TypeElement) element, processingEnv));
            filterClass(classes, ElementFilter.typesIn(element.getEnclosedElements()));
        }
    }
}
 
Example 18
Source Project: netbeans   Source File: ElementNode.java    License: Apache License 2.0 5 votes vote down vote up
public Description(@NonNull String name,
        @NonNull ElementHandle<? extends Element> elementHandle,
        @NonNull ElementKind kind,
        boolean inherited) {
    assert name != null;
    assert elementHandle != null;
    assert kind != null;
    this.name = name;
    this.elementHandle = elementHandle;
    this.kind = kind;
    this.inherited = inherited;
    this.selected = Boolean.FALSE;
}
 
Example 19
Source Project: netbeans   Source File: EventInjectionPointLogic.java    License: Apache License 2.0 5 votes vote down vote up
private List<VariableElement> getEventInjectionPoints( )
{
    final List<VariableElement> eventInjection = new LinkedList<VariableElement>();
    try {
        getModel().getHelper().getAnnotationScanner().findAnnotations(INJECT_ANNOTATION, 
                EnumSet.of( ElementKind.FIELD),  new AnnotationHandler() {
                    
                    @Override
                    public void handleAnnotation( TypeElement type, 
                            Element element, AnnotationMirror annotation )
                    {
                       Element typeElement = getCompilationController().getTypes().
                               asElement( element.asType() );
                        if ( typeElement instanceof TypeElement && 
                                element instanceof VariableElement )
                        {
                            Name name = ((TypeElement)typeElement).getQualifiedName();
                            if ( EVENT_INTERFACE.contentEquals( name )){
                                eventInjection.add( (VariableElement) element);
                            }
                        }
                    }
                });
    }
    catch (InterruptedException e) {
        LOGGER.warning("Finding annotation @Inject was interrupted"); // NOI18N
    }
    return eventInjection;
}
 
Example 20
Source Project: immutables   Source File: Proto.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Checks if this element is a regular POJO (not an interface or abstract class) simple
 * class with getters and setters
 */
@Value.Derived
@Value.Auxiliary
public boolean isJavaBean() {
  return element().getKind().isClass()
      &&
      element().getKind() != ElementKind.ENUM
      &&
      !element().getModifiers().contains(Modifier.PRIVATE)
      &&
      !element().getModifiers().contains(Modifier.ABSTRACT)
      &&
      // restrict to Criteria and Repository annotations for now
      (CriteriaMirror.find(element()).isPresent() || CriteriaRepositoryMirror.find(element()).isPresent());
}
 
Example 21
@Override
public Void visitExecutable(ExecutableElement method, Object o) {
    // Methods must be public
    if (!method.getModifiers().contains(Modifier.PUBLIC))
        return null;
    if (processedMethod(method))
        return null;
    WebMethod webMethod = method.getAnnotation(WebMethod.class);
    if (webMethod != null && webMethod.exclude())
        return null;
    SOAPBinding soapBinding = method.getAnnotation(SOAPBinding.class);
    if (soapBinding == null && !method.getEnclosingElement().equals(typeElement)) {
        if (method.getEnclosingElement().getKind().equals(ElementKind.CLASS)) {
            soapBinding = method.getEnclosingElement().getAnnotation(SOAPBinding.class);
            if (soapBinding != null)
                builder.log("using " + method.getEnclosingElement() + "'s SOAPBinding.");
            else {
                soapBinding = new MySoapBinding();
            }
        }
    }
    boolean newBinding = false;
    if (soapBinding != null) {
        newBinding = pushSoapBinding(soapBinding, method, typeElement);
    }
    try {
        if (shouldProcessMethod(method, webMethod)) {
            processMethod(method, webMethod);
        }
    } finally {
        if (newBinding) {
            popSoapBinding();
        }
    }
    return null;
}
 
Example 22
Source Project: netbeans   Source File: EqualsHashCodeGenerator.java    License: Apache License 2.0 5 votes vote down vote up
static EqualsHashCodeGenerator createEqualsHashCodeGenerator(JTextComponent component, CompilationController cc, Element el) throws IOException {
    if (el.getKind() != ElementKind.CLASS) {
        return null;
    }
    //#125114: ignore anonymous innerclasses:
    if (el.getSimpleName() == null || el.getSimpleName().length() == 0) {
        return null;
    }
    TypeElement typeElement = (TypeElement)el;
    
    ExecutableElement[] equalsHashCode = overridesHashCodeAndEquals(cc, typeElement, null);
    
    List<ElementNode.Description> descriptions = new ArrayList<>();
    for (VariableElement variableElement : ElementFilter.fieldsIn(typeElement.getEnclosedElements())) {
        if (!ERROR.contentEquals(variableElement.getSimpleName()) && !variableElement.getModifiers().contains(Modifier.STATIC)) {
            descriptions.add(ElementNode.Description.create(cc, variableElement, null, true, isUsed(cc, variableElement, equalsHashCode)));
        }
    }
    if (descriptions.isEmpty() || (equalsHashCode[0] != null && equalsHashCode[1] != null)) {
        return null;
    }
    return new EqualsHashCodeGenerator(
        component,
        ElementNode.Description.create(cc, typeElement, descriptions, false, false),
        equalsHashCode[0] == null,
        equalsHashCode[1] == null
    );
}
 
Example 23
Source Project: netbeans   Source File: EditorContextImpl.java    License: Apache License 2.0 5 votes vote down vote up
/** throws IllegalComponentStateException when can not return the data in AWT. */
private String getCurrentElement(final ElementKind kind, final String[] elementSignaturePtr)
        throws java.awt.IllegalComponentStateException {
    return getCurrentElement(contextDispatcher.getCurrentFile(),
                             contextDispatcher.getCurrentEditor(),
                             kind, elementSignaturePtr);
}
 
Example 24
private TypeElement outermostTypeElement(Element el) {
    while (el.getEnclosingElement().getKind() != ElementKind.PACKAGE) {
        el = el.getEnclosingElement();
    }

    return (TypeElement) el;
}
 
Example 25
Source Project: netbeans   Source File: ComputeImports.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Void visitNewClass(NewClassTree node, Map<String, Object> p) {
    filterByNotAcceptedKind(node.getIdentifier(), ElementKind.ENUM);
    scan(node.getEnclosingExpression(), new HashMap<String, Object>());
    scan(node.getIdentifier(), p, true);
    scan(node.getTypeArguments(), new HashMap<String, Object>(), true);
    scan(node.getArguments(), new HashMap<String, Object>());
    scan(node.getClassBody(), new HashMap<String, Object>());
    return null;
}
 
Example 26
Source Project: OnActivityResult   Source File: UtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void isParameter() {
    assertTrue(Utils.isParameter(this.getVariableElement(ElementKind.PARAMETER)));

    assertFalse(Utils.isParameter(this.getVariableElement(ElementKind.METHOD)));
    assertFalse(Utils.isParameter(this.getVariableElement(ElementKind.FIELD)));

    assertFalse(Utils.isParameter(this.getMethodElement(ElementKind.METHOD)));
    assertFalse(Utils.isParameter(this.getMethodElement(ElementKind.FIELD)));
    assertFalse(Utils.isParameter(this.getMethodElement(ElementKind.PARAMETER)));
}
 
Example 27
Source Project: netbeans   Source File: Utilities.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean isJavaString(CompilationInfo ci, TypeMirror m) {
    if (m == null || m.getKind() != TypeKind.DECLARED) {
        return false;
    } 
    Element e = ((DeclaredType)m).asElement();
    return (e.getKind() == ElementKind.CLASS && ((TypeElement)e).getQualifiedName().contentEquals("java.lang.String")); // NOI18N
}
 
Example 28
Source Project: netbeans   Source File: BinaryAnalyser.java    License: Apache License 2.0 5 votes vote down vote up
private static ElementKind getElementKind(@NonNull final ClassFile cf) {
    if (cf.isEnum()) {
        return ElementKind.ENUM;
    } else if (cf.isAnnotation()) {
        return ElementKind.ANNOTATION_TYPE;
    } else if (cf.isModule()) {
        return ElementKind.MODULE;
    } else if ((cf.getAccess() & Access.INTERFACE) == Access.INTERFACE) {
        return ElementKind.INTERFACE;
    } else {
        return ElementKind.CLASS;
    }
}
 
Example 29
Source Project: openjdk-jdk9   Source File: Utils.java    License: GNU General Public License v2.0 5 votes vote down vote up
private DocCommentDuo getDocCommentTuple(Element element) {
    // prevent nasty things downstream with overview element
    if (element.getKind() != ElementKind.OTHER) {
        TreePath path = getTreePath(element);
        if (path != null) {
            DocCommentTree docCommentTree = docTrees.getDocCommentTree(path);
            return new DocCommentDuo(path, docCommentTree);
        }
    }
    return null;
}
 
Example 30
Source Project: dagger2-sample   Source File: MembersInjectionBinding.java    License: Apache License 2.0 5 votes vote down vote up
private InjectionSite injectionSiteForInjectMethod(ExecutableElement methodElement,
    DeclaredType containingType) {
  checkNotNull(methodElement);
  checkArgument(methodElement.getKind().equals(ElementKind.METHOD));
  checkArgument(isAnnotationPresent(methodElement, Inject.class));
  ExecutableType resolved =
      MoreTypes.asExecutable(types.asMemberOf(containingType, methodElement));
  return new AutoValue_MembersInjectionBinding_InjectionSite(InjectionSite.Kind.METHOD,
      methodElement,
      dependencyRequestFactory.forRequiredResolvedVariables(
          containingType,
          methodElement.getParameters(),
          resolved.getParameterTypes()));
}