javax.lang.model.util.ElementFilter Java Examples

The following examples show how to use javax.lang.model.util.ElementFilter. 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 Project: jeddict   Author: jeddict   File: JavaSourceHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static TypeElement getXmlRepresentationClass(TypeElement typeElement, String defaultSuffix) {
    List<ExecutableElement> methods = ElementFilter.methodsIn(typeElement.getEnclosedElements());
    for (ExecutableElement method : methods) {
        List<? extends AnnotationMirror> anmirs = method.getAnnotationMirrors();

        AnnotationMirror mirrorHttpMethod = findAnnotation(anmirs, JAXRSConstants.GET);
        if (mirrorHttpMethod != null) {
            TypeMirror tm = method.getReturnType();
            if (tm != null && tm.getKind() == TypeKind.DECLARED) {
                TypeElement returnType = (TypeElement) ((DeclaredType) tm).asElement();
                if (returnType.getSimpleName().toString().endsWith(defaultSuffix)) {
                    return returnType;
                }
            }
        }
    }
    return null;
}
 
Example #2
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: Gen.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Including super classes' fields.
 */

List<VariableElement> getAllFields(TypeElement subclazz) {
    List<VariableElement> fields = new ArrayList<>();
    TypeElement cd = null;
    Stack<TypeElement> s = new Stack<>();

    cd = subclazz;
    while (true) {
        s.push(cd);
        TypeElement c = (TypeElement) (types.asElement(cd.getSuperclass()));
        if (c == null)
            break;
        cd = c;
    }

    while (!s.empty()) {
        cd = s.pop();
        fields.addAll(ElementFilter.fieldsIn(cd.getEnclosedElements()));
    }

    return fields;
}
 
Example #3
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: JavahTask.java    License: GNU General Public License v2.0 6 votes vote down vote up
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    try {
        Set<TypeElement> classes = getAllClasses(ElementFilter.typesIn(roundEnv.getRootElements()));
        if (classes.size() > 0) {
            checkMethodParameters(classes);
            g.setProcessingEnvironment(processingEnv);
            g.setClasses(classes);
            g.run();
        }
    } catch (CompletionFailure cf) {
        messager.printMessage(ERROR, getMessage("class.not.found", cf.sym.getQualifiedName().toString()));
    } catch (ClassNotFoundException cnfe) {
        messager.printMessage(ERROR, getMessage("class.not.found", cnfe.getMessage()));
    } catch (IOException ioe) {
        messager.printMessage(ERROR, getMessage("io.exception", ioe.getMessage()));
    } catch (Util.Exit e) {
        exit = e;
    }

    return true;
}
 
Example #4
Source Project: TencentKona-8   Author: Tencent   File: JNIWriter.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Including super class fields.
 */
List<VariableElement> getAllFields(TypeElement subclazz) {
    List<VariableElement> fields = new ArrayList<VariableElement>();
    TypeElement cd = null;
    Stack<TypeElement> s = new Stack<TypeElement>();

    cd = subclazz;
    while (true) {
        s.push(cd);
        TypeElement c = (TypeElement) (types.asElement(cd.getSuperclass()));
        if (c == null)
            break;
        cd = c;
    }

    while (!s.empty()) {
        cd = s.pop();
        fields.addAll(ElementFilter.fieldsIn(cd.getEnclosedElements()));
    }

    return fields;
}
 
Example #5
Source Project: netbeans   Author: apache   File: ManagedBeansAnalizer.java    License: Apache License 2.0 6 votes vote down vote up
private void checkCtor( TypeElement element, WebBeansModel model,
       Result result )
{
    List<ExecutableElement> ctors = ElementFilter.constructorsIn( 
            element.getEnclosedElements());
    for (ExecutableElement ctor : ctors) {
        Set<Modifier> modifiers = ctor.getModifiers();
        if ( modifiers.contains( Modifier.PRIVATE )){
            continue;
        }
        List<? extends VariableElement> parameters = ctor.getParameters();
        if ( parameters.size() ==0 ){
            return;
        }
        if ( AnnotationUtil.hasAnnotation(ctor, AnnotationUtil.INJECT_FQN, 
                model.getCompilationController()))
        {
            return;
        }
    }
    // there is no non-private ctors without params or annotated with @Inject
    result.addNotification( Severity.WARNING, element, model, 
            NbBundle.getMessage(ManagedBeansAnalizer.class, 
            "WARN_QualifierNoCtorClass")); // NOI18N
}
 
Example #6
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: T6458749.java    License: GNU General Public License v2.0 6 votes vote down vote up
public boolean process(Set<? extends TypeElement> tes, RoundEnvironment renv) {
    if (!renv.processingOver()) {
        for(TypeElement e : ElementFilter.typesIn(renv.getRootElements())) {
            System.out.printf("Element %s:%n", e.toString());
            try {
                for (TypeParameterElement tp : e.getTypeParameters()) {
                    System.out.printf("Type param %s", tp.toString());
                    if (! tp.getEnclosedElements().isEmpty()) {
                        throw new AssertionError("TypeParameterElement.getEnclosedElements() should return empty list");
                    }
                }
            } catch (NullPointerException npe) {
                throw new AssertionError("NPE from TypeParameterElement.getEnclosedElements()", npe);
            }
        }
    }
    return true;
}
 
Example #7
Source Project: auto-parcel   Author: aitorvs   File: AutoParcelProcessor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This method returns a list of all non private fields. If any <code>private</code> fields is
 * found, the method errors out
 *
 * @param type element
 * @return list of all non-<code>private</code> fields
 */
private List<VariableElement> getParcelableFieldsOrError(TypeElement type) {
    List<VariableElement> allFields = ElementFilter.fieldsIn(type.getEnclosedElements());
    List<VariableElement> nonPrivateFields = new ArrayList<>();

    for (VariableElement field : allFields) {
        if (!field.getModifiers().contains(PRIVATE)) {
            nonPrivateFields.add(field);
        } else {
            // return error, PRIVATE fields are not allowed
            mErrorReporter.abortWithError("getFieldsError error, PRIVATE fields not allowed", type);
        }
    }

    return nonPrivateFields;
}
 
Example #8
Source Project: doma   Author: domaframework   File: InternalDomainMetaFactory.java    License: Apache License 2.0 6 votes vote down vote up
void validateConstructor(TypeElement classElement, DomainMeta domainMeta) {
  for (ExecutableElement constructor :
      ElementFilter.constructorsIn(classElement.getEnclosedElements())) {
    if (constructor.getModifiers().contains(Modifier.PRIVATE)) {
      continue;
    }
    List<? extends VariableElement> parameters = constructor.getParameters();
    if (parameters.size() != 1) {
      continue;
    }
    TypeMirror parameterType = ctx.getMoreTypes().erasure(parameters.get(0).asType());
    if (ctx.getMoreTypes().isSameTypeWithErasure(parameterType, domainMeta.getValueType())) {
      return;
    }
  }
  throw new AptException(
      Message.DOMA4103, classElement, new Object[] {domainMeta.getValueType()});
}
 
Example #9
Source Project: openjdk-8-source   Author: keerath   File: Gen.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Including super classes' fields.
 */

List<VariableElement> getAllFields(TypeElement subclazz) {
    List<VariableElement> fields = new ArrayList<VariableElement>();
    TypeElement cd = null;
    Stack<TypeElement> s = new Stack<TypeElement>();

    cd = subclazz;
    while (true) {
        s.push(cd);
        TypeElement c = (TypeElement) (types.asElement(cd.getSuperclass()));
        if (c == null)
            break;
        cd = c;
    }

    while (!s.empty()) {
        cd = s.pop();
        fields.addAll(ElementFilter.fieldsIn(cd.getEnclosedElements()));
    }

    return fields;
}
 
Example #10
Source Project: RetroFacebook   Author: yongjhih   File: TypeSimplifierTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testIsCastingUnchecked() {
  TypeElement erasureClass = typeElementOf("Erasure");
  List<VariableElement> fields = ElementFilter.fieldsIn(erasureClass.getEnclosedElements());
  for (VariableElement field : fields) {
    String fieldName = field.getSimpleName().toString();
    boolean expectUnchecked;
    if (fieldName.endsWith("Yes")) {
      expectUnchecked = true;
    } else if (fieldName.endsWith("No")) {
      expectUnchecked = false;
    } else {
      throw new AssertionError("Fields in Erasure class must end with Yes or No: " + fieldName);
    }
    TypeMirror fieldType = field.asType();
    boolean actualUnchecked = TypeSimplifier.isCastingUnchecked(fieldType);
    assertEquals("Unchecked-cast status for " + fieldType, expectUnchecked, actualUnchecked);
  }
}
 
Example #11
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: JNIWriter.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Including super class fields.
 */
List<VariableElement> getAllFields(TypeElement subclazz) {
    List<VariableElement> fields = new ArrayList<VariableElement>();
    TypeElement cd = null;
    Stack<TypeElement> s = new Stack<TypeElement>();

    cd = subclazz;
    while (true) {
        s.push(cd);
        TypeElement c = (TypeElement) (types.asElement(cd.getSuperclass()));
        if (c == null)
            break;
        cd = c;
    }

    while (!s.empty()) {
        cd = s.pop();
        fields.addAll(ElementFilter.fieldsIn(cd.getEnclosedElements()));
    }

    return fields;
}
 
Example #12
Source Project: openjdk-8-source   Author: keerath   File: JavahTask.java    License: GNU General Public License v2.0 6 votes vote down vote up
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    try {
        Set<TypeElement> classes = getAllClasses(ElementFilter.typesIn(roundEnv.getRootElements()));
        if (classes.size() > 0) {
            checkMethodParameters(classes);
            g.setProcessingEnvironment(processingEnv);
            g.setClasses(classes);
            g.run();
        }
    } catch (CompletionFailure cf) {
        messager.printMessage(ERROR, getMessage("class.not.found", cf.sym.getQualifiedName().toString()));
    } catch (ClassNotFoundException cnfe) {
        messager.printMessage(ERROR, getMessage("class.not.found", cnfe.getMessage()));
    } catch (IOException ioe) {
        messager.printMessage(ERROR, getMessage("io.exception", ioe.getMessage()));
    } catch (Util.Exit e) {
        exit = e;
    }

    return true;
}
 
Example #13
Source Project: sundrio   Author: sundrio   File: TypeDefUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCombineTwoTerminal() throws Exception {
    TypeElement typeElement = elements.getTypeElement(TwoTerminal.class.getCanonicalName());
    List<ExecutableElement> methods = ElementFilter.methodsIn(typeElement.getEnclosedElements());
    ExecutableElement left = methods.get(0);
    ExecutableElement right = methods.get(1);
    TypeDef leftClazz = executableToInterface(dslContext, left);
    TypeDef rightClazz = executableToInterface(dslContext, right);
    TypeDef combined = Combine.TYPEDEFS.apply(Arrays.asList(leftClazz, rightClazz));
    Assert.assertNotNull(combined);

    Assert.assertThat(combined.getName(), CoreMatchers.equalTo("MethodABInterface"));
    Assert.assertThat(combined.getPackageName(), CoreMatchers.equalTo(getClass().getPackage().getName()));
    //Assert.assertThat(combined.getParameters().size(), CoreMatchers.is(1));
    Assert.assertThat(combined.getExtendsList().size(), CoreMatchers.is(2));
    Assert.assertThat(combined.getExtendsList(), CoreMatchers.hasItem(TypeNamed.typeNamed("public interface MethodAInterface<T>")));
    Assert.assertThat(combined.getExtendsList(), CoreMatchers.hasItem(TypeNamed.typeNamed("public interface MethodBInterface<T>")));
    assertEquals(combined.getAttributes().get(ORIGINAL_RETURN_TYPE), TRANSPARENT_REF);
}
 
Example #14
Source Project: netbeans   Author: apache   File: GeneratorUtilitiesTest.java    License: Apache License 2.0 6 votes vote down vote up
public void validate(CompilationInfo info) {
    TypeElement test = info.getElements().getTypeElement("test.Test");

    boolean foundCloneMethod = false;
    boolean foundToStringMethod = false;

    for (ExecutableElement ee : ElementFilter.methodsIn(test.getEnclosedElements())) {
        if (ee.getSimpleName().contentEquals("clone")) {
            if (ee.getParameters().isEmpty()) {
                assertFalse(foundCloneMethod);
                foundCloneMethod = true;
            }
        } else if (ee.getSimpleName().contentEquals("toString")) {
            if (ee.getParameters().isEmpty()) {
                assertFalse(foundToStringMethod);
                foundToStringMethod = true;
            }
        }
    }

    assertTrue(foundCloneMethod);
    assertTrue(foundToStringMethod);
}
 
Example #15
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: WebServiceVisitor.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected boolean classImplementsSei(TypeElement classElement, TypeElement interfaceElement) {
    for (TypeMirror interfaceType : classElement.getInterfaces()) {
        if (((DeclaredType) interfaceType).asElement().equals(interfaceElement))
            return true;
    }
    List<ExecutableElement> classMethods = getClassMethods(classElement);
    boolean implementsMethod;
    for (ExecutableElement interfaceMethod : ElementFilter.methodsIn(interfaceElement.getEnclosedElements())) {
        implementsMethod = false;
        for (ExecutableElement classMethod : classMethods) {
            if (sameMethod(interfaceMethod, classMethod)) {
                implementsMethod = true;
                classMethods.remove(classMethod);
                break;
            }
        }
        if (!implementsMethod) {
            builder.processError(WebserviceapMessages.WEBSERVICEAP_METHOD_NOT_IMPLEMENTED(interfaceElement.getSimpleName(), classElement.getSimpleName(), interfaceMethod), interfaceMethod);
            return false;
        }
    }
    return true;
}
 
Example #16
Source Project: netbeans   Author: apache   File: PatternAnalyser.java    License: Apache License 2.0 6 votes vote down vote up
private void resolveTypes(Parameters p) {
    
    List<TypeElement> types = ElementFilter.typesIn(p.element.getEnclosedElements());
    
    for (TypeElement typeElement : types) {
        if ( typeElement.getKind() == ElementKind.CLASS ||
             typeElement.getKind() == ElementKind.INTERFACE ) {
            PatternAnalyser pa = new PatternAnalyser( p.ci.getFileObject(), ui );
            pa.analyzeAll(p.ci, typeElement);
            ClassPattern cp = new ClassPattern(pa, typeElement.asType(), 
                                               BeanUtils.nameAsString(typeElement));
            currentClassesPatterns.add(cp);
        }
    }

    
}
 
Example #17
Source Project: netbeans   Author: apache   File: ResourceImplTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testSimplyAnnotatedField() throws Exception {
    TestUtilities.copyStringToFileObject(srcFO, "MyClass.java",
            "public class MyClass {" +
            "   @javax.annotation.Resource" +
            "   private javax.sql.DataSource myResource;" +
            "}");
    IndexingManager.getDefault().refreshIndexAndWait(srcFO.getURL(), null);
    ClasspathInfo cpi = ClasspathInfo.create(srcFO);
    final AnnotationModelHelper annotationModelHelper = AnnotationModelHelper.create(cpi);
    annotationModelHelper.runJavaSourceTask(new Runnable() {
        public void run() {
            TypeElement myClass = annotationModelHelper.getCompilationController().getElements().getTypeElement("MyClass");
            List<VariableElement> fields = ElementFilter.fieldsIn(myClass.getEnclosedElements());
            VariableElement annotatedField = fields.get(0);
            
            ResourceImpl resource = new ResourceImpl(annotatedField, myClass, annotationModelHelper);
            assertEquals("myResource", resource.getName());
            assertEquals("javax.sql.DataSource", resource.getType());
            assertEquals(ResourceImpl.DEFAULT_AUTHENTICATION_TYPE, resource.getAuthenticationType());
            assertEquals(ResourceImpl.DEFAULT_SHAREABLE, resource.getShareable());
            assertEquals(ResourceImpl.DEFAULT_MAPPED_NAME, resource.getMappedName());
            assertEquals(ResourceImpl.DEFAULT_DESCRIPTION, resource.getDescription());
        }
    });
}
 
Example #18
Source Project: netbeans   Author: apache   File: ScopedBeanAnalyzer.java    License: Apache License 2.0 6 votes vote down vote up
private void checkPublicField( TypeElement scopeElement, Element element,
        WebBeansModel model, Result result )
{
    if ( AnnotationUtil.DEPENDENT.contentEquals( 
            scopeElement.getQualifiedName()))
    {
        return;
    }
    result.requireCdiEnabled(element, model);
    List<VariableElement> fields = ElementFilter.fieldsIn( 
            element.getEnclosedElements());
    for (VariableElement field : fields) {
        Set<Modifier> modifiers = field.getModifiers();
        if ( modifiers.contains(Modifier.PUBLIC )
                && (!modifiers.contains(Modifier.STATIC) || !model.isCdi11OrLater())){
            result.addError(element, model ,  
                    NbBundle.getMessage(ScopedBeanAnalyzer.class,
                        "ERR_IcorrectScopeWithPublicField", 
                        field.getSimpleName().toString()));
            return;
        }
    }
}
 
Example #19
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: ElementsTable.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the "requires" modules for the target module.
 * @param mdle the target module element
 * @param onlyTransitive true gets all the requires transitive, otherwise
 *                 gets all the non-transitive requires
 *
 * @return a set of modules
 */
private Set<ModuleElement> getModuleRequires(ModuleElement mdle, boolean onlyTransitive) throws ToolException {
    Set<ModuleElement> result = new HashSet<>();
    for (RequiresDirective rd : ElementFilter.requiresIn(mdle.getDirectives())) {
        ModuleElement dep = rd.getDependency();
        if (result.contains(dep))
            continue;
        if (!isMandated(mdle, rd) && onlyTransitive == rd.isTransitive()) {
            if (!haveModuleSources(dep)) {
                messager.printWarning(dep, "main.module_not_found", dep.getSimpleName());
            }
            result.add(dep);
        } else if (isMandated(mdle, rd) && haveModuleSources(dep)) {
            result.add(dep);
        }
    }
    return result;
}
 
Example #20
Source Project: jlibs   Author: santhosh-tekuri   File: BindingAnnotationProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private void process(Binding binding, TypeElement c){
    for(ExecutableElement method: ElementFilter.methodsIn(c.getEnclosedElements())){
        for(AnnotationMirror mirror: method.getAnnotationMirrors()){
            if(BINDING_ELEMENT.matches(mirror))
                BINDING_ELEMENT.consume(binding, method, mirror);
            else if(BINDING_START.matches(mirror))
                BINDING_START.consume(binding, method, mirror);
            else if(BINDING_TEXT.matches(mirror))
                BINDING_TEXT.consume(binding, method, mirror);
            else if(BINDING_FINISH.matches(mirror))
                BINDING_FINISH.consume(binding, method, mirror);
            else if(RELATION_START.matches(mirror))
                RELATION_START.consume(binding, method, mirror);
            else if(RELATION_FINISH.matches(mirror))
                RELATION_FINISH.consume(binding, method, mirror);
        }
    }
}
 
Example #21
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: TypeModeler.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static TypeElement getDeclaringClassMethod(TypeElement theClass, String methodName, TypeMirror[] args) {

        TypeElement retClass = null;
        if (theClass.getKind().equals(ElementKind.CLASS)) {
            TypeMirror superClass = theClass.getSuperclass();
            if (!superClass.getKind().equals(TypeKind.NONE))
                retClass = getDeclaringClassMethod(superClass, methodName, args);
        }
        if (retClass == null) {
            for (TypeMirror interfaceType : theClass.getInterfaces()) {
                retClass = getDeclaringClassMethod(interfaceType, methodName, args);
            }
        }
        if (retClass == null) {
            Collection<? extends ExecutableElement> methods = ElementFilter.methodsIn(theClass.getEnclosedElements());
            for (ExecutableElement method : methods) {
                if (method.getSimpleName().toString().equals(methodName)) {
                    retClass = theClass;
                    break;
                }
            }
        }
        return retClass;
    }
 
Example #22
Source Project: auto-parcel   Author: aitorvs   File: MoreElements.java    License: Apache License 2.0 6 votes vote down vote up
private static void getLocalAndInheritedMethods(
        PackageElement pkg, TypeElement type, SetMultimap<String, ExecutableElement> methods) {

    for (TypeMirror superInterface : type.getInterfaces()) {
        getLocalAndInheritedMethods(pkg, MoreTypes.asTypeElement(superInterface), methods);
    }
    if (type.getSuperclass().getKind() != TypeKind.NONE) {
        // Visit the superclass after superinterfaces so we will always see the implementation of a
        // method after any interfaces that declared it.
        getLocalAndInheritedMethods(pkg, MoreTypes.asTypeElement(type.getSuperclass()), methods);
    }
    for (ExecutableElement method : ElementFilter.methodsIn(type.getEnclosedElements())) {
        if (!method.getModifiers().contains(Modifier.STATIC)
                && methodVisibleFromPackage(method, pkg)) {
            methods.put(method.getSimpleName().toString(), method);
        }
    }
}
 
Example #23
Source Project: netbeans   Author: apache   File: GeneratorUtilitiesTest.java    License: Apache License 2.0 6 votes vote down vote up
public void run(WorkingCopy copy) throws Exception {
    copy.toPhase(JavaSource.Phase.RESOLVED);
    TreePath tp = copy.getTreeUtilities().pathFor(offset);
    assertTrue(TreeUtilities.CLASS_TREE_KINDS.contains(tp.getLeaf().getKind()));
    ClassTree ct = (ClassTree)tp.getLeaf();
    TypeElement te = (TypeElement)copy.getTrees().getElement(tp);
    assertNotNull(te);
    List<? extends VariableElement> vars = ElementFilter.fieldsIn(te.getEnclosedElements());
    TypeElement sup = (TypeElement)((DeclaredType)te.getSuperclass()).asElement();
    assertNotNull(sup);
    List<? extends ExecutableElement> ctors = sup.getQualifiedName().contentEquals("java.lang.Object")
            ? null : ElementFilter.constructorsIn(sup.getEnclosedElements());
    if (ctors != null)
        numCtorsValidator.accept(ctors.size());
    GeneratorUtilities utilities = GeneratorUtilities.get(copy);
    assertNotNull(utilities);
    ClassTree newCt = utilities.insertClassMember(ct, utilities.createConstructor(te, vars, ctors != null ? ctors.get(ctorToUse) : null));
    copy.rewrite(ct, newCt);
}
 
Example #24
Source Project: netbeans   Author: apache   File: IntroduceLocalExtensionTransformer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean accept(CompilationInfo info, TypeMirror tm) {
    if (!super.accept(info, tm)) {
        return false;
    }

    TypeElement clazz = info.getElements().getTypeElement(fqn);

    if (clazz == null) {
        return false;
    }

    for (ExecutableElement m : ElementFilter.methodsIn(clazz.getEnclosedElements())) {
        if (m.getSimpleName().contentEquals(methodName)) {
            return true;
        }
    }

    return false;
}
 
Example #25
Source Project: openjdk-8   Author: bpupadhyaya   File: MyProcessor.java    License: GNU General Public License v2.0 5 votes vote down vote up
public boolean process(Set<? extends TypeElement> tes, RoundEnvironment renv) {
    if (!renv.processingOver()) {
        for(TypeElement e : ElementFilter.typesIn(renv.getRootElements())) {
            for (TypeParameterElement tp : e.getTypeParameters()) {
                if (tp.getSimpleName().toString().length() > 1) {
                    messager.printMessage(WARNING,
                        "Type param names should be of length 1", tp);
                }
            }
        }
    }
    return true;
}
 
Example #26
Source Project: netbeans   Author: apache   File: EntityManagerGenerationStrategySupport.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets the element representing an annotation of the given type. Searches annotations
 *  declared on class, fields and methods (in that order).
 * @param annotationTypeFqn the fully qualified name of the annotation's type.
 * @return the element or null if no matching annotation was found.
 */
protected Element getAnnotation(final String annotationTypeFqn){
    
    Parameters.notEmpty("annotationTypeFqn", annotationTypeFqn); //NOI18N
    
    TypeElement annotationType = asTypeElement(annotationTypeFqn);
    TypeElement classElement = getClassElement();
    List<Element> elements = new ArrayList<Element>();
    elements.add(classElement);
    elements.addAll(ElementFilter.fieldsIn(classElement.getEnclosedElements()));
    elements.addAll(ElementFilter.methodsIn(classElement.getEnclosedElements()));
    
    
    return checkElementsForAnnotationType(elements, annotationType);
}
 
Example #27
Source Project: dagger2-sample   Author: yongjhih   File: DependencyRequestMapperTest.java    License: Apache License 2.0 5 votes vote down vote up
private List<? extends VariableElement> sampleProducerParameters() {
  TypeElement moduleElement =
      elements.getTypeElement(ProducesMethodModule.class.getCanonicalName());
  ExecutableElement producesMethod =
      Iterables.getOnlyElement(ElementFilter.methodsIn(moduleElement.getEnclosedElements()));
  return producesMethod.getParameters();
}
 
Example #28
Source Project: netbeans   Author: apache   File: TestMethodNameGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Collects names of accessible no-argument methods that are present
 * in the given class and its superclasses. Methods inherited from the
 * class's superclasses are taken into account, too.
 * 
 * @param  clazz  class whose methods' names should be collected
 * @param  reservedMethodNames  collection to which the method names
 *                              should be added
 */
private void collectExistingMethodNames(TypeElement clazz,
                                        Collection<String> reservedMethodNames) {
    final Elements elements = workingCopy.getElements();
    List<? extends Element> allMembers = elements.getAllMembers(clazz);
    List<? extends ExecutableElement> methods = ElementFilter.methodsIn(allMembers);
    if (!methods.isEmpty()) {
        for (ExecutableElement method : methods) {
            if (method.getParameters().isEmpty()) {
                reservedMethodNames.add(method.getSimpleName().toString());
            }
        }
    }
}
 
Example #29
Source Project: netbeans   Author: apache   File: GeneratorUtilitiesTest.java    License: Apache License 2.0 5 votes vote down vote up
public void validate(CompilationInfo info) {
    TypeElement test = info.getElements().getTypeElement("test.Test");
    VariableElement var = ElementFilter.fieldsIn(test.getEnclosedElements()).get(0);
    TypeElement sup = (TypeElement)((DeclaredType)test.getSuperclass()).asElement();
    ExecutableElement supCtor = sup.getQualifiedName().contentEquals("java.lang.Object")
            ? null : ElementFilter.constructorsIn(sup.getEnclosedElements()).get(0);

    List<? extends ExecutableElement> ctors = ElementFilter.constructorsIn(test.getEnclosedElements());
    assertEquals(1, ctors.size());
    ExecutableElement ctor = ctors.get(0);

    assertEquals(supCtor == null ? 1 : 2, ctor.getParameters().size());
    if (supCtor != null)
        assertEquals(supCtor.isVarArgs(), ctor.isVarArgs());
}
 
Example #30
Source Project: hottub   Author: dsrg-uoft   File: JavahTask.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void checkMethodParameters(Set<TypeElement> classes) {
    Types types = processingEnv.getTypeUtils();
    for (TypeElement te: classes) {
        for (ExecutableElement ee: ElementFilter.methodsIn(te.getEnclosedElements())) {
            for (VariableElement ve: ee.getParameters()) {
                TypeMirror tm = ve.asType();
                checkMethodParametersVisitor.visit(tm, types);
            }
        }
    }
}