类javax.lang.model.element.ElementKind源码实例Demo

下面列出了怎么用javax.lang.model.element.ElementKind的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: immutables   文件: Constitution.java
@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());
    }
  }
}
 
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);
        }
    }
}
 
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;
}
 
源代码4 项目: netbeans   文件: ResolvedJavaSymbolDescriptor.java
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;
}
 
源代码5 项目: Auto-Dagger2   文件: ComponentProcessing.java
@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;
}
 
源代码6 项目: picocli   文件: DynamicProxyConfigGenerator.java
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());
    }
}
 
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();
    }
 
源代码8 项目: hkt   文件: HktProcessor.java
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 + " {}")));
}
 
源代码9 项目: WandFix   文件: InjectObjectField.java
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()));
    }
}
 
源代码10 项目: netbeans   文件: EnumValueCompleter.java
@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;
    }
}
 
源代码11 项目: openjdk-jdk8u   文件: JavacTrees.java
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;
}
 
源代码12 项目: picocli   文件: MixinInfo.java
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);
}
 
源代码13 项目: soabase-halva   文件: ImplicitValue.java
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(")");
    }
}
 
源代码14 项目: openjdk-jdk9   文件: ElementsTable.java
/**
 * 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;
    }
}
 
源代码15 项目: NullAway   文件: AccessPathNullnessPropagation.java
@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);
}
 
源代码16 项目: openjdk-jdk9   文件: NoPrivateTypesExported.java
private TypeElement outermostTypeElement(Element el) {
    while (el.getEnclosingElement().getKind() != ElementKind.PACKAGE) {
        el = el.getEnclosingElement();
    }

    return (TypeElement) el;
}
 
源代码17 项目: openjdk-jdk8u   文件: SchemaGenerator.java
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()));
        }
    }
}
 
源代码18 项目: netbeans   文件: ElementNode.java
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;
}
 
源代码19 项目: netbeans   文件: EventInjectionPointLogic.java
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;
}
 
源代码20 项目: immutables   文件: Proto.java
/**
 * 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());
}
 
源代码21 项目: openjdk-jdk8u   文件: WebServiceVisitor.java
@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;
}
 
源代码22 项目: netbeans   文件: EqualsHashCodeGenerator.java
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
    );
}
 
源代码23 项目: netbeans   文件: EditorContextImpl.java
/** 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);
}
 
源代码24 项目: openjdk-jdk8u   文件: NoPrivateTypesExported.java
private TypeElement outermostTypeElement(Element el) {
    while (el.getEnclosingElement().getKind() != ElementKind.PACKAGE) {
        el = el.getEnclosingElement();
    }

    return (TypeElement) el;
}
 
源代码25 项目: netbeans   文件: ComputeImports.java
@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;
}
 
源代码26 项目: OnActivityResult   文件: UtilsTest.java
@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)));
}
 
源代码27 项目: netbeans   文件: Utilities.java
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
}
 
源代码28 项目: netbeans   文件: BinaryAnalyser.java
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;
    }
}
 
源代码29 项目: openjdk-jdk9   文件: Utils.java
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;
}
 
源代码30 项目: dagger2-sample   文件: MembersInjectionBinding.java
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()));
}