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

The following are Jave code examples for showing how to use getEnclosedElements() of the javax.lang.model.element.TypeElement class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: easybundler   File: BundlerClassInfo.java   Source Code and License Vote up 6 votes
public BundlerClassInfo(TypeElement te) {
    typeElement = te;
    className = ClassName.get(typeElement);

    for (Element e : te.getEnclosedElements()) {
        if (e.getKind() == ElementKind.FIELD) {
            VariableElement ve = (VariableElement) e;
            fields.add(ve);
        }

        if (e.getKind() == ElementKind.METHOD) {
            ExecutableElement ee = (ExecutableElement) e;
            methods.add(ee);
        }
    }
}
 
Example 2
Project: incubator-netbeans   File: JavaUtils.java   Source Code and License Vote up 6 votes
@Override
public TypeElement visitType(TypeElement typeElement, String binaryName) {
    String bName = ElementUtilities.getBinaryName(typeElement);
    if(binaryName.equals(bName)) {
        return typeElement;
    } else if(binaryName.startsWith(bName)) {
        for(Element child : typeElement.getEnclosedElements()) {
            if(!child.getKind().isClass()) {
                continue;
            }
            
            TypeElement retVal = child.accept(this, binaryName);
            if(retVal != null) {
                return retVal;
            }
        }
    }
    
    return null;
}
 
Example 3
Project: openjdk-jdk10   File: Utils.java   Source Code and License Vote up 6 votes
public ExecutableElement overriddenMethod(ExecutableElement method) {
    if (isStatic(method)) {
        return null;
    }
    final TypeElement origin = getEnclosingTypeElement(method);
    for (TypeMirror t = getSuperType(origin);
            t.getKind() == DECLARED;
            t = getSuperType(asTypeElement(t))) {
        TypeElement te = asTypeElement(t);
        if (te == null) {
            return null;
        }
        List<? extends Element> methods = te.getEnclosedElements();
        for (ExecutableElement ee : ElementFilter.methodsIn(methods)) {
            if (configuration.workArounds.overrides(method, ee, origin)) {
                return ee;
            }
        }
        if (t.equals(getObjectType()))
            return null;
    }
    return null;
}
 
Example 4
Project: convalida   File: ConvalidaProcessor.java   Source Code and License Vote up 6 votes
private void parseCompiledR(String respectivePackageName, TypeElement rClass) {
    for (Element element : rClass.getEnclosedElements()) {
        String innerClassName = element.getSimpleName().toString();
        if (innerClassName.equals("string")) {
            for (Element enclosedElement : element.getEnclosedElements()) {
                if (enclosedElement instanceof VariableElement) {
                    VariableElement variableElement = (VariableElement) enclosedElement;
                    Object value = variableElement.getConstantValue();

                    if (value instanceof Integer) {
                        int id = (Integer) value;
                        ClassName rClassName = ClassName.get(elementUtils.getPackageOf(variableElement).toString(), "R", innerClassName);
                        String resourceName = variableElement.getSimpleName().toString();
                        QualifiedId qualifiedId = new QualifiedId(respectivePackageName, id);
                        symbols.put(qualifiedId, new Id(id, rClassName, resourceName));
                    }
                }
            }
        }
    }
}
 
Example 5
Project: arez   File: ProcessorUtil.java   Source Code and License Vote up 6 votes
private static void enumerateFieldElements( @Nonnull final TypeElement element,
                                            @Nonnull final Map<String, VariableElement> fields )
{
  final TypeMirror superclass = element.getSuperclass();
  if ( TypeKind.NONE != superclass.getKind() )
  {
    enumerateFieldElements( (TypeElement) ( (DeclaredType) superclass ).asElement(), fields );
  }
  for ( final Element member : element.getEnclosedElements() )
  {
    if ( member.getKind() == ElementKind.FIELD )
    {
      fields.put( member.getSimpleName().toString(), (VariableElement) member );
    }
  }
}
 
Example 6
Project: r-parser   File: RParser.java   Source Code and License Vote up 6 votes
private void parseCompiledR(String respectivePackageName, TypeElement rClass) {
    for (Element element : rClass.getEnclosedElements()) {
        String innerClassName = element.getSimpleName().toString();
        if (supportedTypes.contains(innerClassName)) {
            for (Element enclosedElement : element.getEnclosedElements()) {
                if (enclosedElement instanceof VariableElement) {
                    VariableElement variableElement = (VariableElement) enclosedElement;
                    Object value = variableElement.getConstantValue();

                    if (value instanceof Integer) {
                        int id = (Integer) value;
                        ClassName rClassName = ClassName.get(elementUtils.getPackageOf(variableElement).toString(), "R", innerClassName);
                        String resourceName = variableElement.getSimpleName().toString();
                        QualifiedId qualifiedId = new QualifiedId(respectivePackageName, id);
                        symbols.put(qualifiedId, new Id(id, rClassName, resourceName));
                    }
                }
            }
        }
    }
}
 
Example 7
Project: incubator-netbeans   File: TestGeneratorSetup.java   Source Code and License Vote up 6 votes
/**
 */
private boolean hasTestableMethods(TypeElement classElem) {
    List<? extends Element> enclosedElems = classElem.getEnclosedElements();
    if (enclosedElems.isEmpty()) {
        return false;
    }
    
    List<ExecutableElement> methods = ElementFilter.methodsIn(enclosedElems);
    if (methods.isEmpty()) {
        return false;
    }
    
    for (ExecutableElement method : methods) {
        if (isMethodTestable(method)) {
            return true;
        }
    }
    
    return false;
}
 
Example 8
Project: incubator-netbeans   File: PersistentObjectManagerMultipleTest.java   Source Code and License Vote up 5 votes
public List<ResourceImpl> createInitialObjects() {
    final List<ResourceImpl> result = new ArrayList<ResourceImpl>();
    TypeElement departmentType = helper.getCompilationController().getElements().getTypeElement("foo.Department");
    for (Element element : departmentType.getEnclosedElements()) {
        if (isResource(element)) {
            result.add(new ResourceImpl(helper, departmentType, element));
        }
    }
    return result;
}
 
Example 9
Project: incubator-netbeans   File: TestMethodNameGenerator.java   Source Code and License Vote up 5 votes
/**
 * Returns a list of methods contained directly in the given class.
 * 
 * @param  classElem  class whose methods should be returned
 * @return  list of methods in the given class
 */
private static List<ExecutableElement> getExistingMethods(
                                final TypeElement classElem) {
    List<? extends Element> elements = classElem.getEnclosedElements();
    if (elements.isEmpty()) {
        return Collections.<ExecutableElement>emptyList();
    }

    List<ExecutableElement> methods = ElementFilter.methodsIn(elements);
    return !methods.isEmpty() ? methods
                              : Collections.<ExecutableElement>emptyList();
}
 
Example 10
Project: incubator-netbeans   File: AttributesHelper.java   Source Code and License Vote up 5 votes
public AttributesHelper(AnnotationModelHelper helper, TypeElement typeElement, PropertyHandler propertyHandler) {
    this.helper = helper;
    this.typeElement = typeElement;
    this.propertyHandler = propertyHandler;
    if (typeElement == null) {
        fieldAccess = true;
        return;
    }
    List<? extends Element> elements = typeElement.getEnclosedElements();
    fieldAccess = EntityMappingsUtilities.hasFieldAccess(helper, elements);
}
 
Example 11
Project: openjdk-jdk10   File: DupOk.java   Source Code and License Vote up 5 votes
List<Element> getFields(TypeElement klass) {
    List<Element> out = new ArrayList<>();
    for (Element e : klass.getEnclosedElements()) {
        if (e.getKind() == ElementKind.FIELD) {
            out.add(e);
        }
    }
    return out;
}
 
Example 12
Project: incubator-netbeans   File: SrcFinder.java   Source Code and License Vote up 5 votes
/** Gets the method we are looking for
 */
private static ElementHandle findMethod(CompilationController ctrl, TypeElement ce, String member) {
    TreeUtilities utils = ctrl.getTreeUtilities();

    int pi = member.indexOf( '(' );
    String name = member.substring( 0, pi );

    StringTokenizer tokenizer = new StringTokenizer( member.substring( pi ), " ,()" ); // NOI18N
    List<TypeMirror> paramList = new ArrayList<TypeMirror>();

    while( tokenizer.hasMoreTokens() ) {
        String token = tokenizer.nextToken();
        if (token.endsWith("...")) { // NOI18N
            // translate varargs to array
            token = token.substring(0, token.length() - 3);
            token += "[]"; // NOI18N
        }
        TypeMirror type = utils.parseType(token, ce);
        paramList.add(type);
    }
    
    // search method or constructor
    for (Element e: ce.getEnclosedElements()) {
        if (e.getKind() == ElementKind.METHOD
                && name.equals(e.getSimpleName().toString())
                && compareTypes(ctrl, paramList, ((ExecutableElement) e).getParameters())) {
            return ElementHandle.create(e);
        } else if (e.getKind() == ElementKind.CONSTRUCTOR
                && name.equals(ce.getSimpleName().toString())
                && compareTypes(ctrl, paramList, ((ExecutableElement) e).getParameters())) {
            return ElementHandle.create(e);
        }
    }
    
    return null;
}
 
Example 13
Project: incubator-netbeans   File: ToStringGenerator.java   Source Code and License Vote up 5 votes
@Override
public List<? extends CodeGenerator> create(Lookup context) {
    ArrayList<CodeGenerator> ret = new ArrayList<>();
    JTextComponent component = context.lookup(JTextComponent.class);
    CompilationController controller = context.lookup(CompilationController.class);
    if (component == null || controller == null) {
        return ret;
    }
    TreePath path = context.lookup(TreePath.class);
    path = path != null ? controller.getTreeUtilities().getPathElementOfKind(TreeUtilities.CLASS_TREE_KINDS, path) : null;
    if (path == null) {
        return ret;
    }
    try {
        controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
    } catch (IOException ioe) {
        return ret;
    }
    TypeElement typeElement = (TypeElement) controller.getTrees().getElement(path);
    if (typeElement == null || !typeElement.getKind().isClass()) {
        return ret;
    }
    List<ElementNode.Description> descriptions = new ArrayList<>();
    for (Element element : typeElement.getEnclosedElements()) {
        switch (element.getKind()) {
            case METHOD:
                if (element.getSimpleName().contentEquals("toString") && ((ExecutableElement) element).getParameters().isEmpty()) { //NOI18N
                    return ret;
                }
                break;
            case FIELD:
                if (!ERROR.contentEquals(element.getSimpleName()) && !element.getModifiers().contains(Modifier.STATIC)) {
                    descriptions.add(ElementNode.Description.create(controller, element, null, true, true));
                }
        }
    }
    ret.add(new ToStringGenerator(component, ElementNode.Description.create(controller, typeElement, descriptions, false, false)));
    return ret;
}
 
Example 14
Project: GeneratorX   File: GeneratorProcessor.java   Source Code and License Vote up 5 votes
private AnnotatedClass buildAnnotatedClass(TypeElement typeElement) throws
        NoPackageNameException, IOException {

    HashMap<String, TypeMirror> variableMap = new HashMap<>();
    ArrayList<String> variableNames = new ArrayList<>();
    for (Element element : typeElement.getEnclosedElements()) {
        //过滤 字段 的Element
        if (!(element instanceof VariableElement)) {
            continue;
        }
        //过滤 static final 字段
        if (element.getModifiers().contains(STATIC) || element.getModifiers().contains(FINAL)) {
            continue;
        }
        VariableElement variableElement = (VariableElement) element;
        variableNames.add(variableElement.getSimpleName().toString());
        variableMap.put(
                variableElement.getSimpleName().toString(),
                variableElement.asType()
        );
    }

    //打印 用于测试 是否为 parcelable
    if (isParcelable(typeElement)) {
        String message = String.format("Classes %s is parceleble.", ANNOTATION);
        //messager.printMessage(Diagnostic.Kind.OTHER, message, typeElement);
    }
    return new AnnotatedClass(typeElement, variableNames, variableMap,
            isParcelable(typeElement));
}
 
Example 15
Project: GitHub   File: MethodProcessor.java   Source Code and License Vote up 5 votes
public boolean isCallbackMethodAnnotationValid(Element element, String annotationName) {
    TypeElement enclosingElement = (TypeElement)element.getEnclosingElement();

    if (enclosingElement.getAnnotation(JsonObject.class) == null) {
        error(enclosingElement, "%s: @%s methods can only be in classes annotated with @%s.", enclosingElement.getQualifiedName(), annotationName, JsonObject.class.getSimpleName());
        return false;
    }

    ExecutableElement executableElement = (ExecutableElement)element;
    if (executableElement.getParameters().size() > 0) {
        error(element, "%s: @%s methods must not take any parameters.", enclosingElement.getQualifiedName(), annotationName);
        return false;
    }

    List<? extends Element> allElements = enclosingElement.getEnclosedElements();
    int methodInstances = 0;
    for (Element enclosedElement : allElements) {
        for (AnnotationMirror am : enclosedElement.getAnnotationMirrors()) {
            if (am.getAnnotationType().asElement().getSimpleName().toString().equals(annotationName)) {
                methodInstances++;
            }
        }
    }
    if (methodInstances != 1) {
        error(element, "%s: There can only be one @%s method per class.", enclosingElement.getQualifiedName(), annotationName);
        return false;
    }

    return true;
}
 
Example 16
Project: incubator-netbeans   File: StaticImport.java   Source Code and License Vote up 5 votes
/**
 * @param info
 * @param simpleName of static method.
 * @return true if a static import exists with the same simple name.
 * Caveat, expect false positives on protected and default visibility methods from wildcard static imports.
 */
private static boolean hasStaticImportSimpleNameClash(CompilationInfo info, String simpleName) {
    for (ImportTree i : info.getCompilationUnit().getImports()) {
        if (!i.isStatic()) {
            continue;
        }
        String q = i.getQualifiedIdentifier().toString();
        if (q.endsWith(".*")) { //NOI18N
            TypeElement ie = info.getElements().getTypeElement(q.substring(0, q.length() - 2));
            if (ie == null) {
                continue;
            }
            for (Element enclosed : ie.getEnclosedElements()) {
                Set<Modifier> modifiers = enclosed.getModifiers();
                if (enclosed.getKind() != ElementKind.METHOD || !modifiers.contains(Modifier.STATIC) || modifiers.contains(Modifier.PRIVATE)) {
                    continue;
                }
                String sn1 = enclosed.getSimpleName().toString();
                if (simpleName.equals(sn1)) {
                    return true;
                }
            }
        } else {
            int endIndex = q.lastIndexOf("."); //NOI18N
            if (endIndex == -1 || endIndex >= q.length() - 1) {
                continue;
            }
            if (q.substring(endIndex).equals(simpleName)) {
                return true;
            }
        }
    }
    return false;
}
 
Example 17
Project: GitHub   File: AttributeBuilderReflection.java   Source Code and License Vote up 4 votes
/**
 * @return strategy which has an AttributeBuilderDescriptor if attributeValue is an attributeBuilder.
 */
static ThirdPartyAttributeBuilderStrategy of(ValueAttribute valueAttribute) {
  TypeElement attributeValueType = valueAttribute.containedTypeElement;
  if (attributeValueType == null) {
    return ImmutableThirdPartyAttributeBuilderStrategy.of(null, null);
  }

  // Map of possible builder class to needed methods.
  Map<TypeElement, AttributeBuilderThirdPartyModel.Creator> partiallyBuiltModels = new HashMap<>();
  for (Element possibleBuilderMethodCopyMethodOrClass
      : attributeValueType.getEnclosedElements()) {
    AttributeBuilderThirdPartyModel.Creator newBuilderModel = ModifiableCreator.create();

    if (isPossibleBuilderClass(possibleBuilderMethodCopyMethodOrClass, valueAttribute)) {
      newBuilderModel.builderType((TypeElement) possibleBuilderMethodCopyMethodOrClass);
    } else if (isPossibleBuilderMethod(possibleBuilderMethodCopyMethodOrClass, true, valueAttribute)) {
      newBuilderModel
          .builderMethod((ExecutableElement) possibleBuilderMethodCopyMethodOrClass);
    } else if (isPossibleCopyMethod(valueAttribute,
        possibleBuilderMethodCopyMethodOrClass, true)) {
      newBuilderModel
          .copyMethod((ExecutableElement) possibleBuilderMethodCopyMethodOrClass);
    }

    // We found something on the loop interesting
    if (newBuilderModel.findBuilderType() != null) {
      AttributeBuilderThirdPartyModel.Creator maybeCompleteModel;

      if (partiallyBuiltModels.containsKey(newBuilderModel.findBuilderType())) {
        AttributeBuilderThirdPartyModel.Creator partiallyBuiltModel = partiallyBuiltModels
            .get(newBuilderModel.findBuilderType());
        partiallyBuiltModel.mergeFrom(newBuilderModel);
        maybeCompleteModel = partiallyBuiltModel;
      } else {
        processPossibleBuilder(valueAttribute, newBuilderModel);
        partiallyBuiltModels.put(newBuilderModel.findBuilderType(), newBuilderModel);
        maybeCompleteModel = newBuilderModel;
      }

      if (maybeCompleteModel.complete()) {
        return ImmutableThirdPartyAttributeBuilderStrategy.of(maybeCompleteModel.toImmutable(), valueAttribute.containedTypeElement);
      }
    }
  }

  return ImmutableThirdPartyAttributeBuilderStrategy.of(null, null);
}
 
Example 18
Project: GitHub   File: Encodings.java   Source Code and License Vote up 4 votes
private boolean processClass(TypeElement type) {
  if (BuilderMirror.isPresent(type)) {
    this.typeBuilder = type;

    if (!typeParams.equals(getTypeParameterNames(type))
        || !type.getModifiers().contains(Modifier.STATIC)) {
      reporter.withElement(type)
          .error("@Encoding.Builder class '%s' should be static with"
              + " the same type parameters as encoding type: %s",
              type.getSimpleName(),
              typesReader.parameters);

      return true;
    }

    for (Element member : type.getEnclosedElements()) {
      if ((member.getKind() == ElementKind.FIELD
          || member.getKind() == ElementKind.METHOD)
          && !memberNames.add(memberPath(member))) {
        reporter.withElement(member)
            .error(memberPath(member)
                + ": Duplicate builder member name '%s'."
                + " Encoding has limitation so that any duplicate method names are not supported,"
                + " even when allowed by JLS: methods cannot have overloads here."
                + " @Encoding.Naming annotation could be used so that actually generated methods might have the same name"
                + " if they are not conflicting as per JLS overload rules",
                member.getSimpleName());
        continue;
      }

      if (member.getKind() == ElementKind.FIELD) {
        if (processBuilderField((VariableElement) member))
          continue;
      }

      if (member.getKind() == ElementKind.METHOD) {
        if (processBuilderMethod((ExecutableElement) member))
          continue;
      }

      if (member.getKind() == ElementKind.INSTANCE_INIT) {
        continue;
      }

      if (member.getSimpleName().contentEquals("<init>")) {
        continue;
      }

      reporter.withElement(member)
          .warning("Unrecognized Builder member '%s' will be ignored", member.getSimpleName());
    }
    return true;
  }
  return false;
}
 
Example 19
Project: autojackson   File: ComplexDeserializerCreator.java   Source Code and License Vote up 4 votes
/**
 * Loads the constructs needed to create the implementation of the deserialization method
 * <br></br>
 * This method was split out to essentially handle all of the validation needed to perform
 * before the complex deserialization class can be implemented.
 * <br></br>
 * After this method has been called any needed constructs should be returned, or no
 * data returned, with any applicable errors already logged.
 *
 * @param typeElement The main interface being deserialized
 * @return An optional containing the needed constructs if no errors were found
 */
private Optional<DeserializationConstructs> loadConstructs(TypeElement typeElement) {
    TypeElement enumTypeElement = this.processorUtil.getTypeElement(typeElement.getAnnotation(AutoJackson.class));

    Optional<ExecutableElement> methodReturningEnum = loadEnumMethod(typeElement, enumTypeElement);
    if (!methodReturningEnum.isPresent()) {
        this.processorUtil.error(typeElement, "There must be a single method returning %s inside %s", enumTypeElement, typeElement);
        return Optional.empty();
    }

    if (enumTypeElement.getKind() != ElementKind.ENUM) {
        this.processorUtil.error(enumTypeElement, "The type of object for %s must be an enum", AutoJackson.Type.class.getSimpleName());
        return Optional.empty();
    }

    ImmutableList.Builder<Element> constantElementsBuilder = ImmutableList.builder();
    ImmutableList.Builder<ExecutableElement> accessorMethodBuilder = ImmutableList.builder();

    List<? extends Element> enclosedElements = enumTypeElement.getEnclosedElements();
    enclosedElements.forEach(enclosedElement -> {
        if (enclosedElement.getKind() == ElementKind.ENUM_CONSTANT) {
            constantElementsBuilder.add(enclosedElement);
        }
        if (enclosedElement.getAnnotation(AutoJacksonTypeClass.class) != null && enclosedElement.getKind() == ElementKind.METHOD) {
            accessorMethodBuilder.add((ExecutableElement) enclosedElement);
        }
    });

    ImmutableList<Element> enumValueElements = constantElementsBuilder.build();
    ImmutableList<ExecutableElement> enumAccessorElement = accessorMethodBuilder.build();

    if (enumValueElements.isEmpty()) {
        this.processorUtil.error(enumTypeElement, "The enum inside the type must have some values");
        return Optional.empty();
    }

    if (enumAccessorElement.size() != 1) {
        this.processorUtil.error(enumTypeElement, "No accessor method inside enumeration with %s annotaiton", AutoJacksonTypeClass.class);
        return Optional.empty();
    }

    return Optional.of(new DeserializationConstructs(enumTypeElement, enumValueElements, methodReturningEnum.get(), enumAccessorElement.get(0)));
}
 
Example 20
Project: incubator-netbeans   File: AbstractTestGenerator.java   Source Code and License Vote up 4 votes
/**
 */
private List<ExecutableElement> findTestableMethods(WorkingCopy wc, TypeElement classElem) {
    boolean isEJB = isClassEjb31Bean(wc, classElem);
    final Types types = wc.getTypes();

    Iterable<? extends Element> elements;
    if (isEJB){
        final TypeMirror typeObject = wc.getElements().getTypeElement("java.lang.Object").asType(); //NOI18N
        ElementAcceptor acceptor = new ElementAcceptor(){
            public boolean accept(Element e, TypeMirror type) {
                return !types.isSameType(typeObject, e.getEnclosingElement().asType());
            }
        };
        elements = wc.getElementUtilities().getMembers(classElem.asType(), acceptor);
    } else {
        elements = classElem.getEnclosedElements();
    }
    List<ExecutableElement> methods = ElementFilter.methodsIn(elements);

    if (methods.isEmpty()) {
        return Collections.<ExecutableElement>emptyList();
    }

    List<ExecutableElement> testableMethods = null;

    int skippedCount = 0;
    for (ExecutableElement method : methods) {
        if (isTestableMethod(method) &&
                (!isEJB || (isEJB && isTestableEJBMethod(method)))) {
            if (testableMethods == null) {
                testableMethods = new ArrayList<ExecutableElement>(
                                         methods.size() - skippedCount);
            }
            testableMethods.add(method);
        } else {
            skippedCount++;
        }
    }

    return (testableMethods != null)
           ? testableMethods
           : Collections.<ExecutableElement>emptyList();
}