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

The following examples show how to use javax.lang.model.element.Element#getEnclosedElements() . 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: 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 2
Source File: GetTestClass.java    From Mockery with Apache License 2.0 6 votes vote down vote up
private List<Method> getMethods(Element classElement) {
  List<? extends Element> enclosedElements = classElement.getEnclosedElements();
  List<Method> methods = new ArrayList<>();

  for (Element methodElement : enclosedElements) {
    if (methodElement.getKind() != ElementKind.METHOD) continue;
    Symbol.MethodSymbol methodSymbol = (Symbol.MethodSymbol) methodElement;

    if (skipTest(methodSymbol)) continue;

    String name = methodSymbol.getSimpleName().toString();
    TypeName returnType = TypeName.get(methodSymbol.getReturnType());
    List<Param> params = getParams(methodSymbol);

    Mockery mockery = getAnnotation(methodSymbol, Mockery.class);

    methods.add(new Method(name, methodElement,
        returnType, params, mockery != null));
  }

  return methods;
}
 
Example 3
Source File: EventTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void bindingMembersCheck( WebBeansModel model ) {
    TypeMirror mirror = model.resolveType("foo.TestClass1");
    Element clazz = ((DeclaredType) mirror).asElement();
    List<? extends Element> children = clazz.getEnclosedElements();
    List<ExecutableElement> methods = ElementFilter.methodsIn( children );
    assertEquals(2, methods.size());
    for (ExecutableElement method : methods) {
        Name simpleName = method.getSimpleName();
        List<VariableElement> eventInjectionPoints = model.
            getEventInjectionPoints( method, (DeclaredType) mirror);
        assertEquals("Observer "+simpleName+" matches "+eventInjectionPoints.size()
                +" events. But should match exactly one", 1, eventInjectionPoints.size());
        VariableElement variableElement = eventInjectionPoints.get(0);
        TypeElement containingType = model.getCompilationController().
            getElementUtilities().enclosingTypeElement( variableElement);
        Name varName = variableElement.getSimpleName();
        assertEquals("Event injection point should be inside class foo.Clazz," +
        		"but found inside "+ containingType.getQualifiedName(), 
        		"foo.Clazz",  containingType.getQualifiedName().toString());
        assertEquals("Observer method "+simpleName+" should match to" +
            		" event field 'event', but found :"+varName, "event",  varName.toString());
    }
    
}
 
Example 4
Source File: MarkdownGenerator.java    From copybara with Apache License 2.0 6 votes vote down vote up
private ImmutableList<DocFlag> generateFlagsInfo(Element classElement) throws ElementException {
  ImmutableList.Builder<DocFlag> result = ImmutableList.builder();
  AnnotationHelper<UsesFlags> annotation = annotationHelper(classElement, UsesFlags.class);
  if (annotation == null) {
    return result.build();
  }
  for (DeclaredType flag : annotation.getClassListValue("value")) {
    Element flagClass = flag.asElement();
    for (Element member : flagClass.getEnclosedElements()) {
      Parameter flagAnnotation = member.getAnnotation(Parameter.class);
      if (flagAnnotation == null
          || !(member instanceof VariableElement)
          || flagAnnotation.hidden()) {
        continue;
      }
      result.add(new DocFlag(Joiner.on(", ").join(flagAnnotation.names()),
          simplerJavaTypes(member.asType()), flagAnnotation.description()));
    }
  }
  return result.build();
}
 
Example 5
Source File: TableEntry.java    From RapidORM with Apache License 2.0 6 votes vote down vote up
private void buildAllColumns(Element element) {
    if (null == element) {
        return;
    }
    List<? extends Element> eles = element.getEnclosedElements();
    for (Element e : eles) {
        if (ElementKind.FIELD == e.getKind()) {
            if (e.getModifiers().contains(Modifier.PRIVATE)) {
                throw new RuntimeException(e.getSimpleName().toString() + " in " + element.asType().toString() + " CAN NOT be private!");
            }
            Column column = e.getAnnotation(Column.class);
            if (null != column) {
                mColumnList.add(new ColumnEntry(e, element));
            }
        }
    }
}
 
Example 6
Source File: AbstractCommandSpecProcessor.java    From picocli with Apache License 2.0 6 votes vote down vote up
private boolean isSubcommand(ExecutableElement method, RoundEnvironment roundEnv) {
    Element typeElement = method.getEnclosingElement();
    if (typeElement.getAnnotation(Command.class) != null && typeElement.getAnnotation(Command.class).addMethodSubcommands()) {
        return true;
    }
    if (typeElement.getAnnotation(Command.class) == null) {
        Set<Element> elements = new HashSet<Element>(typeElement.getEnclosedElements());

        // The class is a Command if it has any fields or methods annotated with the below:
        return roundEnv.getElementsAnnotatedWith(Option.class).removeAll(elements)
                || roundEnv.getElementsAnnotatedWith(Parameters.class).removeAll(elements)
                || roundEnv.getElementsAnnotatedWith(Mixin.class).removeAll(elements)
                || roundEnv.getElementsAnnotatedWith(ArgGroup.class).removeAll(elements)
                || roundEnv.getElementsAnnotatedWith(Unmatched.class).removeAll(elements)
                || roundEnv.getElementsAnnotatedWith(Spec.class).removeAll(elements);
    }
    return false;
}
 
Example 7
Source File: TraverseProc.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void addPublicTypes(List<TypeElement> list, Element e) {
    ElementKind kind = e.getKind();
    if ((kind.isClass() || kind.isInterface())
            && e.getModifiers().contains(Modifier.PUBLIC)) {
        list.add((TypeElement)e);
        for (Element enc : e.getEnclosedElements()) {
            addPublicTypes(list, enc);
        }
    }
}
 
Example 8
Source File: BindingDetector.java    From AutoBundle with Apache License 2.0 5 votes vote down vote up
private static String findSetterMethod(Element classElement,
                                       VariableElement fieldElement,
                                       AutoBundleField fieldAnnotation) {
    final String operation = "set";
    final String argKeyName = fieldAnnotation.key().length() > 0
            ? fieldAnnotation.key() : fieldElement.toString();
    for (Element element : classElement.getEnclosedElements()) {
        final String methodName = element.getSimpleName().toString();
        AutoBundleSetter annotation = element.getAnnotation(AutoBundleSetter.class);
        if (annotation != null) {
            // annotated setter
            if (argKeyName.equals(annotation.key())) {
                // check modifier
                if (element.getModifiers().contains(Modifier.PRIVATE)) {
                    throw new ProcessingException("@AutoBundleSetter must not be private");
                }
                return methodName;
            }
        } else {
            // default setter
            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 9
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean visitSwitch(SwitchTree node, Void p) {
    boolean lastCaseExit = false;
    boolean defaultSeen = false;
    Set<Element> enumValues = null;
    
    if (node.getExpression() != null) {
        TypeMirror exprType = info.getTrees().getTypeMirror(new TreePath(getCurrentPath(), node.getExpression()));
        if (isValidType(exprType) && exprType.getKind() == TypeKind.DECLARED) {
            Element el = ((DeclaredType)exprType).asElement();
            enumValues = new HashSet<>();
            for (Element f : el.getEnclosedElements()) {
                if (f.getKind() == ElementKind.ENUM_CONSTANT) {
                    enumValues.add(f);
                }
            }
        }
    }
    for (CaseTree ct : node.getCases()) {
        Boolean res = scan(ct, null);
        if (res == Boolean.FALSE) {
            return res;
        }
        lastCaseExit = res == Boolean.TRUE;
        if (ct.getExpression() == null) {
            defaultSeen = true;
        } else if (enumValues != null ) {
            TreePath casePath = new TreePath(getCurrentPath(), ct);
            Element v = info.getTrees().getElement(new TreePath(
                    casePath, ct.getExpression()));
            if (v != null) {
                enumValues.remove(v);
            }
        }
    }
    if (enumValues != null && enumValues.isEmpty()) {
        defaultSeen = true;
    }
    return lastCaseExit == Boolean.TRUE && defaultSeen;
}
 
Example 10
Source File: Utils.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private List<Element> getItems0(Element te, boolean filter, Set<ElementKind> kinds) {
    List<Element> elements = new ArrayList<>();
    for (Element e : te.getEnclosedElements()) {
        if (kinds.contains(e.getKind())) {
            if (!filter || shouldDocument(e)) {
                elements.add(e);
            }
        }
    }
    return elements;
}
 
Example 11
Source File: TestTreePath.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations,
        RoundEnvironment roundEnv) {
    final Trees trees = Trees.instance(this.processingEnv);
    for (Element element : ElementFilter.typesIn(roundEnv.getRootElements())) {
        checkTreePath(trees, element, 2);
        for (Element member : element.getEnclosedElements())
            checkTreePath(trees, member, 3);
    }
    return true;
}
 
Example 12
Source File: HTMLDialogProcessor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void searchSubTree(
        Element e,
        Set<Element> found,
        Class<? extends Annotation> type
) {
    if (e.getAnnotation(type) != null) {
        found.add(e);
    }
    for (Element ee : e.getEnclosedElements()) {
        searchSubTree(ee, found, type);
    }
}
 
Example 13
Source File: NamedServiceProcessor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static ExecutableElement findAttribute(Element e, String attrName) {
    for (Element attr : e.getEnclosedElements()) {
        if (attr.getKind() == ElementKind.METHOD && attr.getSimpleName().contentEquals(attrName)) {
            return (ExecutableElement)attr;
        }
    }
    return null;
}
 
Example 14
Source File: BindProcessor.java    From PlusDemo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    for (Element element : roundEnv.getRootElements()) {
        String packageStr = element.getEnclosingElement().toString();
        String classStr = element.getSimpleName().toString();
        ClassName className = ClassName.get(packageStr, classStr + "$Binding");
        MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder()
                .addModifiers(Modifier.PUBLIC)
                .addParameter(ClassName.get(packageStr, classStr), "activity");
        boolean hasBinding = false;

        for (Element enclosedElement : element.getEnclosedElements()) {
            BindView bindView = enclosedElement.getAnnotation(BindView.class);
            if (bindView != null) {
                hasBinding = true;
                constructorBuilder.addStatement("activity.$N = activity.findViewById($L)",
                        enclosedElement.getSimpleName(), bindView.value());
            }
        }

        TypeSpec builtClass = TypeSpec.classBuilder(className)
                .addModifiers(Modifier.PUBLIC)
                .addMethod(constructorBuilder.build())
                .build();

        if (hasBinding) {
            try {
                JavaFile.builder(packageStr, builtClass)
                        .build().writeTo(filer);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return false;
}
 
Example 15
Source File: TestTreePath.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations,
        RoundEnvironment roundEnv) {
    final Trees trees = Trees.instance(this.processingEnv);
    for (Element element : ElementFilter.typesIn(roundEnv.getRootElements())) {
        checkTreePath(trees, element, 2);
        for (Element member : element.getEnclosedElements())
            checkTreePath(trees, member, 3);
    }
    return true;
}
 
Example 16
Source File: TestTreePath.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations,
        RoundEnvironment roundEnv) {
    final Trees trees = Trees.instance(this.processingEnv);
    for (Element element : ElementFilter.typesIn(roundEnv.getRootElements())) {
        checkTreePath(trees, element, 2);
        for (Element member : element.getEnclosedElements())
            checkTreePath(trees, member, 3);
    }
    return true;
}
 
Example 17
Source File: CasquatchEntityProcessor.java    From casquatch with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a Statement Factory class
 * @param className object holding an entity class
 * @throws Exception exception generated while creating source
 */
private void writeStatementFactory(String className, String tableName) throws Exception {
    Map<String, Object> input = inputStart(className);
    Map<String,String> keyFields = new HashMap<>();
    Map<String,String> nonKeyFields = new HashMap<>();
    Map<String,String> udtFields = new HashMap<>();

    List<String> imports = new ArrayList<>();

    for (Element element : roundEnv.getRootElements()) {
        if (element.getSimpleName().toString().equals(CasquatchNamingConvention.classToSimpleClass(className))) {
            for (Element enclosedElement : element.getEnclosedElements()) {
                if (enclosedElement.getKind().equals(ElementKind.FIELD)) {
                    if(
                            enclosedElement.getAnnotation(com.fasterxml.jackson.annotation.JsonIgnore.class)==null &&
                            enclosedElement.getAnnotation(com.tmobile.opensource.casquatch.annotation.CasquatchIgnore.class)==null
                    ) {

                        String type = "";
                        if(enclosedElement.asType().getKind()== TypeKind.DECLARED) {
                            type=processingEnv.getTypeUtils().erasure(enclosedElement.asType()).toString();
                            for(TypeMirror typeMirror : ((DeclaredType)enclosedElement.asType()).getTypeArguments()) {
                                if (!imports.contains(typeMirror.toString())) imports.add(typeMirror.toString());
                            }
                        }
                        else {
                            type=enclosedElement.asType().toString();
                        }
                        if (!imports.contains(type)) imports.add(type);

                        if(enclosedElement.getAnnotation(com.tmobile.opensource.casquatch.annotation.PartitionKey.class)!=null) {
                            keyFields.put(enclosedElement.getSimpleName().toString(),type);
                        }
                        else if(enclosedElement.getAnnotation(com.tmobile.opensource.casquatch.annotation.ClusteringColumn.class)!=null) {
                            keyFields.put(enclosedElement.getSimpleName().toString(),type);
                        }
                        else if(enclosedElement.getAnnotation(com.tmobile.opensource.casquatch.annotation.UDT.class)!=null) {
                            udtFields.put(enclosedElement.getSimpleName().toString(),type);
                            if (!imports.contains("com.datastax.oss.driver.api.core.data.UdtValue")) imports.add("com.datastax.oss.driver.api.core.data.UdtValue");
                        }
                        else {
                            nonKeyFields.put(enclosedElement.getSimpleName().toString(),type);
                        }
                    }
                }
            }
        }
    }

    if(!tableName.isEmpty()) {
        input.put("table",tableName);
    }
    else {
        input.put("table", CasquatchNamingConvention.javaVariableToCql(CasquatchNamingConvention.classToVar(CasquatchNamingConvention.classToSimpleClass(className))));
    }
    input.put("imports",imports);
    input.put("keyFields", keyFields);
    input.put("udtFields", udtFields);
    input.put("nonKeyFields", nonKeyFields);
    createSource(CasquatchNamingConvention.classToStatementFactory(className),"StatementFactory.ftl",input);
}
 
Example 18
Source File: RouterProcessor.java    From JIMU with Apache License 2.0 4 votes vote down vote up
private void parseRouteNodes(Set<? extends Element> routeElements) {

        TypeMirror type_Activity = elements.getTypeElement(ACTIVITY).asType();

        for (Element element : routeElements) {
            TypeMirror tm = element.asType();
            RouteNode route = element.getAnnotation(RouteNode.class);

            if (types.isSubtype(tm, type_Activity)) {                 // Activity
                logger.info(">>> Found activity route: " + tm.toString() + " <<<");

                Node node = new Node();
                String path = route.path();

                checkPath(path);

                node.setPath(path);
                node.setDesc(route.desc());
                node.setPriority(route.priority());
                node.setNodeType(NodeType.ACTIVITY);
                node.setRawType(element);

                Map<String, Integer> paramsType = new HashMap<>();
                Map<String, String> paramsDesc = new HashMap<>();
                for (Element field : element.getEnclosedElements()) {
                    if (field.getKind().isField() && field.getAnnotation(Autowired.class) != null) {
                        Autowired paramConfig = field.getAnnotation(Autowired.class);
                        paramsType.put(StringUtils.isEmpty(paramConfig.name())
                                ? field.getSimpleName().toString() : paramConfig.name(), typeUtils.typeExchange(field));
                        paramsDesc.put(StringUtils.isEmpty(paramConfig.name())
                                ? field.getSimpleName().toString() : paramConfig.name(), typeUtils.typeDesc(field));
                    }
                }
                node.setParamsType(paramsType);
                node.setParamsDesc(paramsDesc);

                if (!routerNodes.contains(node)) {
                    routerNodes.add(node);
                }
            } else {
                throw new IllegalStateException("only activity can be annotated by RouteNode");
            }
        }
    }
 
Example 19
Source File: ComponentProcessor.java    From appinventor-extensions with Apache License 2.0 4 votes vote down vote up
private void processEvents(ComponentInfo componentInfo,
                           Element componentElement) {
  for (Element element : componentElement.getEnclosedElements()) {
    if (!isPublicMethod(element)) {
      continue;
    }

    // Get the name of the prospective event.
    String eventName = element.getSimpleName().toString();
    processConditionalAnnotations(componentInfo, element, eventName);

    SimpleEvent simpleEventAnnotation = element.getAnnotation(SimpleEvent.class);

    // Remove overriden events unless SimpleEvent is again specified.
    // See comment in processProperties for an example.
    if (simpleEventAnnotation == null) {
      if (componentInfo.events.containsKey(eventName)) {
        componentInfo.events.remove(eventName);
      }
    } else {
      String eventDescription = simpleEventAnnotation.description();
      String longEventDescription = elementUtils.getDocComment(element);
      if (eventDescription.isEmpty()) {
        eventDescription = longEventDescription;
        if (eventDescription == null) {
          messager.printMessage(Diagnostic.Kind.WARNING,
                                "In component " + componentInfo.name +
                                ", event " + eventName +
                                " is missing a description.");
          eventDescription = "";
        }
      }
      boolean userVisible = simpleEventAnnotation.userVisible();
      boolean deprecated = elementUtils.isDeprecated(element);
      Event event = new Event(eventName, eventDescription, longEventDescription, userVisible, deprecated);
      componentInfo.events.put(event.name, event);

      // Verify that this element has an ExecutableType.
      if (!(element instanceof ExecutableElement)) {
        throw new RuntimeException("In component " + componentInfo.name +
                                   ", the representation of SimpleEvent " + eventName +
                                   " does not implement ExecutableElement.");
      }
      ExecutableElement e = (ExecutableElement) element;

      // Extract the parameters.
      for (VariableElement ve : e.getParameters()) {
        event.addParameter(ve.getSimpleName().toString(),
                           ve.asType().toString(),
                           ve.getAnnotation(IsColor.class) != null);
        updateComponentTypes(ve.asType());
      }
    }
  }
}
 
Example 20
Source File: SpotCompiler.java    From spot with Apache License 2.0 4 votes vote down vote up
/**
 * Generate YourModel$$Repository class
 * @param element
 * @throws IOException
 */
private void generateRepositoryClass(Element element) throws IOException {
    String packageName = elements.getPackageOf(element).getQualifiedName().toString();
    ClassName entityClass = ClassName.get(packageName, element.getSimpleName().toString());
    ClassName stringClass = ClassName.get(String.class);
    ClassName contextClass = ClassName.get(Context.class);
    ClassName utilClass = ClassName.get(PreferencesUtil.class);

    Pref prefAnnotation = element.getAnnotation(Pref.class);
    String tableName = prefAnnotation.name();

    MethodSpec constructorSpec = MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PRIVATE)
            .build();

    MethodSpec getNameSpec = MethodSpec.methodBuilder("getName")
            .addModifiers(Modifier.PRIVATE, Modifier.FINAL, Modifier.STATIC)
            .returns(stringClass)
            .addStatement("return $S", tableName)
            .build();

    MethodSpec.Builder getEntitySpecBuilder = MethodSpec.methodBuilder("getEntity")
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL, Modifier.STATIC)
            .addParameter(contextClass, "context")
            .returns(entityClass)
            .addStatement("$T entity = new $T()", entityClass, entityClass);

    MethodSpec.Builder putEntitySpecBuilder = MethodSpec.methodBuilder("putEntity")
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL, Modifier.STATIC)
            .addParameter(contextClass, "context")
            .addParameter(entityClass, "entity");

    MethodSpec.Builder clearSpecBuilder = MethodSpec.methodBuilder("clear")
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL, Modifier.STATIC)
            .addParameter(contextClass, "context")
            .addStatement("$T.clear(context, getName())",
                    utilClass);

    for (Element element1 : element.getEnclosedElements()) {
        if (element1.getAnnotation(PrefField.class) != null) {
            handlePrefField(element1, getEntitySpecBuilder, putEntitySpecBuilder);
        }
    }

    getEntitySpecBuilder.addStatement("return entity");

    String className = element.getSimpleName() + "SpotRepository";
    TypeSpec repository = TypeSpec.classBuilder(className)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addMethod(constructorSpec)
            .addMethod(getNameSpec)
            .addMethod(getEntitySpecBuilder.build())
            .addMethod(putEntitySpecBuilder.build())
            .addMethod(clearSpecBuilder.build())
            .build();

    JavaFile.builder(packageName, repository)
            .build()
            .writeTo(filer);
}