javax.lang.model.element.ElementKind Java Examples

The following examples show how to use javax.lang.model.element.ElementKind. 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: ImplicitValue.java    From soabase-halva with 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 #2
Source File: ResolvedJavaSymbolDescriptor.java    From netbeans with 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 #3
Source File: DynamicProxyConfigGenerator.java    From picocli with 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 #4
Source File: Constitution.java    From immutables with 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 #5
Source File: AnnotationsProcessor.java    From android-transformer with 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 #6
Source File: MixinInfo.java    From picocli with 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 #7
Source File: InjectObjectField.java    From WandFix with 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 #8
Source File: JavacTrees.java    From openjdk-jdk8u with 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 #9
Source File: ConvertToLambdaPreconditionChecker.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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 #10
Source File: AngeliaLoadAnnotationProcessor.java    From Angelia-core with GNU General Public License v3.0 6 votes vote down vote up
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 #11
Source File: ComponentProcessing.java    From Auto-Dagger2 with 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 #12
Source File: EnumValueCompleter.java    From netbeans with 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 #13
Source File: HktProcessor.java    From hkt with 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 #14
Source File: XPFlagCleaner.java    From piranha with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("TreeToString")
@Override
public Description matchImport(ImportTree importTree, VisitorState visitorState) {
  if (importTree.isStatic()) {
    Tree importIdentifier = importTree.getQualifiedIdentifier();
    if (importIdentifier.getKind().equals(Kind.MEMBER_SELECT)) {
      MemberSelectTree memberSelectTree = (MemberSelectTree) importIdentifier;
      if (memberSelectTree.getIdentifier().toString().endsWith(xpFlagName)
          || (treatmentGroupsEnum != null
              && memberSelectTree.getExpression().toString().startsWith(treatmentGroupsEnum))) {
        return buildDescription(importTree)
            .addFix(SuggestedFix.replace(importTree, "", 0, 1))
            .build();
      } else if (treatmentGroup.length() > 0 && treatmentGroupsEnum == null) {
        // Check if this import is for values in the same enum that includes the treatmentGroup
        Symbol importSymbol = ASTHelpers.getSymbol(memberSelectTree.getExpression());
        if (importSymbol.getKind().equals(ElementKind.ENUM)
            && isTreatmentGroupEnum((Symbol.ClassSymbol) importSymbol)) {
          treatmentGroupsEnum = ((Symbol.ClassSymbol) importSymbol).fullname.toString();
          return buildDescription(importTree)
              .addFix(SuggestedFix.replace(importTree, "", 0, 1))
              .build();
        }
      }
    }
  }
  return Description.NO_MATCH;
}
 
Example #15
Source File: InjectPresenterProcessor.java    From Moxy with MIT License 5 votes vote down vote up
private static List<TargetPresenterField> collectFields(TypeElement presentersContainer) {
	List<TargetPresenterField> fields = new ArrayList<>();

	for (Element element : presentersContainer.getEnclosedElements()) {
		if (element.getKind() != ElementKind.FIELD) {
			continue;
		}

		AnnotationMirror annotation = Util.getAnnotation(element, PRESENTER_FIELD_ANNOTATION);

		if (annotation == null) {
			continue;
		}

		// TODO: simplify?
		TypeMirror clazz = ((DeclaredType) element.asType()).asElement().asType();

		String name = element.toString();

		String type = Util.getAnnotationValueAsString(annotation, "type");
		String tag = Util.getAnnotationValueAsString(annotation, "tag");
		String presenterId = Util.getAnnotationValueAsString(annotation, "presenterId");

		TargetPresenterField field = new TargetPresenterField(clazz, name, type, tag, presenterId);
		fields.add(field);
	}
	return fields;
}
 
Example #16
Source File: TransportProcessor.java    From transport with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void processElements(Set<? extends Element> elements) {
  for (Element element : elements) {
    // Check if the element is a non-abstract class which extends the StdUDF class
    if (element.getKind().equals(ElementKind.CLASS) && !element.getModifiers().contains(Modifier.ABSTRACT)
        && _types.isAssignable(element.asType(), _stdUDFClassType)) {
      processUDFClass((TypeElement) element);
    }
  }
}
 
Example #17
Source File: StateProcessor.java    From android-state with Eclipse Public License 1.0 5 votes vote down vote up
private Element findElement(Element element, ElementKind kind) {
    Element enclosingElement = element.getEnclosingElement();
    if (enclosingElement == null) {
        return element;
    }
    return element.getKind() == kind ? element : findElement(enclosingElement, kind);
}
 
Example #18
Source File: ManagedAnnotationValidator.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv)
{
    Elements elementUtils = processingEnv.getElementUtils();
    Types typeUtils = processingEnv.getTypeUtils();

    TypeElement annotationElement = elementUtils.getTypeElement(MANAGED_ANNOTATION_CLASS_NAME);

    String className = "org.apache.qpid.server.model.ManagedInterface";
    TypeMirror configuredObjectType = getErasure(className);

    for (Element e : roundEnv.getElementsAnnotatedWith(annotationElement))
    {
        if (e.getKind() != ElementKind.INTERFACE)
        {
            processingEnv.getMessager()
                    .printMessage(Diagnostic.Kind.ERROR,
                                  "@"
                                  + annotationElement.getSimpleName()
                                  + " can only be applied to an interface",
                                  e
                                 );
        }


        if(!typeUtils.isAssignable(typeUtils.erasure(e.asType()), configuredObjectType))
        {

            processingEnv.getMessager()
                    .printMessage(Diagnostic.Kind.ERROR,
                                  "@"
                                  + annotationElement.getSimpleName()
                                  + " can only be applied to an interface which extends " + className,
                                  e
                                 );
        }
    }

    return false;
}
 
Example #19
Source File: CreateClassFix.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static int valueForBundle(ElementKind kind) {
    switch (kind) {
    case CLASS:
        return 0;
    case INTERFACE:
        return 1;
    case ENUM:
        return 2;
    case ANNOTATION_TYPE:
        return 3;
    default:
        assert false : kind;
        return 0;
    }
}
 
Example #20
Source File: Flow.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean visitMethodInvocation(MethodInvocationTree node, ConstructorData p) {
    super.visitMethodInvocation(node, p);

    Element invoked = info.getTrees().getElement(getCurrentPath());
    if (invoked != null && invoked.getKind() == ElementKind.METHOD) {
        // Special handling for System.exit: no defined value will escape this code path.
        if (Utilities.isSystemExit(info, invoked)) {
            removeAllDefinitions();
            return null;
        }
        recordResumeOnExceptionHandler((ExecutableElement) invoked);    
    }
    return null;
}
 
Example #21
Source File: ElementTo.java    From sundrio with Apache License 2.0 5 votes vote down vote up
public TypeDef apply(TypeElement classElement) {
    List<ClassRef> extendsList = new ArrayList<ClassRef>();

    //Check SuperClass
    Kind kind = Kind.CLASS;
    if (classElement.getKind() == ElementKind.INTERFACE) {
        kind = Kind.INTERFACE;
    } else if (classElement.getKind() == ElementKind.CLASS) {
        kind = Kind.CLASS;
        extendsList.add(TypeDef.OBJECT_REF);
    } else if (classElement.getKind() == ElementKind.ANNOTATION_TYPE) {
        kind = Kind.ANNOTATION;
    } else if (classElement.getKind() == ElementKind.ENUM) {
        kind = Kind.ENUM;
    }

    Set<Method> allMethods = new LinkedHashSet<Method>();

    for (ExecutableElement method : ElementFilter.methodsIn(classElement.getEnclosedElements())) {
    }
    return new TypeDefBuilder()
            .withKind(kind)
            .withModifiers(TypeUtils.modifiersToInt(classElement.getModifiers()))
            .withPackageName(getPackageName(classElement))
            .withName(getClassName(classElement))
            .withExtendsList(extendsList)
            .addAllToMethods(allMethods)
            .withOuterType(classElement.getEnclosingElement() instanceof TypeElement ? SHALLOW_TYPEDEF.apply((TypeElement) classElement.getEnclosingElement()) : null)
            .build();
}
 
Example #22
Source File: AccessPathNullnessPropagation.java    From NullAway with 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 #23
Source File: GremlinDslProcessor.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
private void validateDSL(final Element dslElement) throws ProcessorException {
    if (dslElement.getKind() != ElementKind.INTERFACE)
        throw new ProcessorException(dslElement, "Only interfaces can be annotated with @%s", GremlinDsl.class.getSimpleName());

    final TypeElement typeElement = (TypeElement) dslElement;
    if (!typeElement.getModifiers().contains(Modifier.PUBLIC))
        throw new ProcessorException(dslElement, "The interface %s is not public.", typeElement.getQualifiedName());
}
 
Example #24
Source File: IntroduceHint.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Crates method formal parameters, following code style conventions.
 * The trees in 'statements' will be rewritten to use the new identifiers.
 * 
 * @param copy working copy
 * @param parameters variables to turn into parameters
 * @param statements trees that should refer to parameters
 * @return 
 */
static List<VariableTree> createVariables(WorkingCopy copy, List<VariableElement> parameters, 
        TreePath targetParent,
        List<TreePath> statements) {
    final TreeMaker make = copy.getTreeMaker();
    List<VariableTree> formalArguments = new LinkedList<VariableTree>();
    CodeStyle cs = CodeStyle.getDefault(copy.getFileObject());
    
    String prefix = cs.getParameterNamePrefix();
    String suffix = cs.getParameterNameSuffix(); 
    Map<VariableElement, CharSequence> renamedVariables = new HashMap<VariableElement, CharSequence>();
    Set<Name> changedNames = new HashSet<Name>();
    for (VariableElement p : parameters) {
        TypeMirror tm = p.asType();
        Tree type = make.Type(tm);
        Name formalArgName = p.getSimpleName();
        Set<Modifier> formalArgMods = EnumSet.noneOf(Modifier.class);
        
        if (p.getModifiers().contains(Modifier.FINAL)) {
            formalArgMods.add(Modifier.FINAL);
        }
        String strippedName = Utilities.stripVariableName(cs, p);
        CharSequence codeStyleName = Utilities.guessName(copy, strippedName, targetParent, prefix, suffix, p.getKind() == ElementKind.PARAMETER);
        if (!formalArgName.contentEquals(codeStyleName)) {
            renamedVariables.put(p, codeStyleName);
            changedNames.add(formalArgName);
        } else {
            codeStyleName = formalArgName;
        }
        formalArguments.add(make.Variable(make.Modifiers(formalArgMods), codeStyleName, type, null));
    }
    if (!changedNames.isEmpty()) {
        VariableRenamer renamer = new VariableRenamer(copy, renamedVariables, changedNames);
        for (TreePath stPath : statements) {
            renamer.scan(stPath, null);
        }
    }
    return formalArguments;
}
 
Example #25
Source File: ModelMethodPlugin.java    From squidb with Apache License 2.0 5 votes vote down vote up
private void checkExecutableElement(ExecutableElement e, List<ExecutableElement> modelMethods,
        List<ExecutableElement> staticModelMethods, DeclaredTypeName modelClass) {
    Set<Modifier> modifiers = e.getModifiers();
    if (e.getKind() == ElementKind.CONSTRUCTOR) {
        // Don't copy constructors
        return;
    }
    if (!modifiers.contains(Modifier.STATIC)) {
        utils.getMessager().printMessage(Diagnostic.Kind.WARNING,
                "Model spec objects should never be instantiated, so non-static methods are meaningless. " +
                        "Did you mean to make this a static method?", e);
        return;
    }
    ModelMethod methodAnnotation = e.getAnnotation(ModelMethod.class);
    // Private static methods may be unannotated if they are called by a public annotated method.
    // Don't assume error if method is private
    if (methodAnnotation == null) {
        if (modifiers.contains(Modifier.PUBLIC)) {
            staticModelMethods.add(e);
        } else if (!modifiers.contains(Modifier.PRIVATE)) {
            utils.getMessager().printMessage(Diagnostic.Kind.WARNING,
                    "This method will not be added to the model definition. " +
                            "Did you mean to annotate this method with @ModelMethod?", e);
        }
    } else {
        List<? extends VariableElement> params = e.getParameters();
        if (params.size() == 0) {
            modelSpec.logError("@ModelMethod methods must have an abstract model as their first argument", e);
        } else {
            VariableElement firstParam = params.get(0);
            TypeMirror paramType = firstParam.asType();
            if (!checkFirstArgType(paramType, modelClass)) {
                modelSpec.logError("@ModelMethod methods must have an abstract model as their first argument", e);
            } else {
                modelMethods.add(e);
            }
        }
    }
}
 
Example #26
Source File: CodeGenProcessor.java    From vertx-codegen with Apache License 2.0 5 votes vote down vote up
private void reportGenException(GenException e) {
  String name = e.element.toString();
  if (e.element.getKind() == ElementKind.METHOD) {
    name = e.element.getEnclosingElement() + "#" + name;
  }
  String msg = "Could not generate model for " + name + ": " + e.msg;
  log.log(Level.SEVERE, msg, e);
  processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, msg, e.element);
}
 
Example #27
Source File: JavadocHelper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
FragmentBuilder(@NonNull ElementKind kind) {
    int size = FILTERS.size();
    // JDK-8046068 changed the constructor format from "Name" to "<init>"
    if (kind == ElementKind.CONSTRUCTOR) {
        size *= 2;
    }
    this.sbs = new StringBuilder[size];
    for (int i = 0; i < sbs.length; i++) {
        sbs[i] = new StringBuilder();
    }
}
 
Example #28
Source File: RestServicesImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public List<RestServiceDescriptionImpl> createInitialObjects() throws InterruptedException {
    //System.out.println("createInitialObjects()");
    final Map<TypeElement, RestServiceDescriptionImpl> result =
            new HashMap<TypeElement, RestServiceDescriptionImpl>();
    
    findAnnotation(RestConstants.PATH, EnumSet.of(ElementKind.CLASS), result);
    findAnnotation(RestConstants.GET, EnumSet.of(ElementKind.METHOD), result);
    findAnnotation(RestConstants.POST, EnumSet.of(ElementKind.METHOD), result);
    findAnnotation(RestConstants.PUT, EnumSet.of(ElementKind.METHOD), result);
    findAnnotation(RestConstants.DELETE, EnumSet.of(ElementKind.METHOD), result);
    
    return new ArrayList<RestServiceDescriptionImpl>(result.values());
}
 
Example #29
Source File: OptionProcessor.java    From bazel with Apache License 2.0 5 votes vote down vote up
/** Check that the Option variables only occur in OptionBase-inheriting classes. */
private void checkInOptionBase(VariableElement optionField) throws OptionProcessorException {
  if (optionField.getEnclosingElement().getKind() != ElementKind.CLASS) {
    throw new OptionProcessorException(optionField, "The field should belong to a class.");
  }
  TypeMirror thisOptionClass = optionField.getEnclosingElement().asType();
  TypeMirror optionsBase =
      elementUtils.getTypeElement("com.google.devtools.common.options.OptionsBase").asType();
  if (!typeUtils.isAssignable(thisOptionClass, optionsBase)) {
    throw new OptionProcessorException(
        optionField,
        "@Option annotated fields can only be in classes that inherit from OptionsBase.");
  }
}
 
Example #30
Source File: Utils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static boolean isProvider(TypeElement type, AnnotationModelHelper helper) {
    if (type.getKind() != ElementKind.INTERFACE) { // don't consider interfaces
        if (helper.hasAnnotation(type.getAnnotationMirrors(),
                RestConstants.PROVIDER_ANNOTATION)) { // NOI18N
            return true;
        }
    }
    return false;
}