javax.lang.model.element.Element Java Examples

The following examples show how to use javax.lang.model.element.Element. 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: JavacTaskImpl.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Complete all analysis on the given classes.
 * This can be used to ensure that all compile time errors are reported.
 * The classes must have previously been returned from {@link #enter}.
 * If null is specified, all outstanding classes will be analyzed.
 *
 * @param classes a list of class elements
 */
// This implementation requires that we open up privileges on JavaCompiler.
// An alternative implementation would be to move this code to JavaCompiler and
// wrap it here
public Iterable<? extends Element> analyze(Iterable<? extends TypeElement> classes) throws IOException {
    enter(null);  // ensure all classes have been entered

    final ListBuffer<Element> results = new ListBuffer<Element>();
    try {
        if (classes == null) {
            handleFlowResults(compiler.flow(compiler.attribute(compiler.todo)), results);
        } else {
            Filter f = new Filter() {
                public void process(Env<AttrContext> env) {
                    handleFlowResults(compiler.flow(compiler.attribute(env)), results);
                }
            };
            f.run(compiler.todo, classes);
        }
    } finally {
        compiler.log.flush();
    }
    return results;
}
 
Example #2
Source File: AnnotationParsers.java    From convalida with Apache License 2.0 6 votes vote down vote up
private static void parseBetweenValidation(
        Element startElement,
        Set<Element> parents,
        List<ValidationField> fields
) {
    boolean hasError = (
            isInvalid(Between.Start.class, startElement) ||
                    isInaccessible(Between.Start.class, startElement)
    ) || (
            isInvalid(Between.Limit.class, startElement) ||
                    isInaccessible(Between.Limit.class, startElement)
    );

    if (hasError) {
        return;
    }

    Element limitElement = validateBetweenStartAnnotation(startElement);

    if (limitElement == null) return;

    parseBetweenStartValidation(startElement, parents, fields);

    parseBetweenLimitValidation(limitElement, parents, fields);
}
 
Example #3
Source File: MoreTypes.java    From auto-parcel with Apache License 2.0 6 votes vote down vote up
@Override
public Integer visitDeclared(DeclaredType t, Set<Element> visiting) {
    Element element = t.asElement();
    if (visiting.contains(element)) {
        return 0;
    }
    Set<Element> newVisiting = new HashSet<Element>(visiting);
    newVisiting.add(element);
    int result = hashKind(HASH_SEED, t);
    result *= HASH_MULTIPLIER;
    result += t.asElement().hashCode();
    result *= HASH_MULTIPLIER;
    result += t.getEnclosingType().accept(this, newVisiting);
    result *= HASH_MULTIPLIER;
    result += hashList(t.getTypeArguments(), newVisiting);
    return result;
}
 
Example #4
Source File: AnnotationProcessor.java    From papercut with Apache License 2.0 6 votes vote down vote up
private boolean versionNameConditionMet(final String versionName, final Element element) {
    // Drop out quickly if there's no versionName set otherwise the try/catch below is doomed to fail.
    if (versionName.isEmpty()) return false;

    int comparison;

    try {
        final Version conditionVersion = Version.valueOf(versionName);
        final Version currentVersion = Version.valueOf(this.versionName);

        comparison = Version.BUILD_AWARE_ORDER.compare(conditionVersion, currentVersion);
    } catch (final IllegalArgumentException | com.github.zafarkhaja.semver.ParseException e) {
        messager.printMessage(Diagnostic.Kind.ERROR, String.format("Failed to parse versionName: %1$s. " +
                "Please use a versionName that matches the specification on http://semver.org/", versionName),
                element);

        // Assume the break condition is met if the versionName is invalid.
        return true;
    }

    return !versionName.isEmpty() && comparison <= 0;
}
 
Example #5
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 #6
Source File: JavacTrees.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public JCTree getTree(Element element) {
    Symbol symbol = (Symbol) element;
    TypeSymbol enclosing = symbol.enclClass();
    Env<AttrContext> env = enter.getEnv(enclosing);
    if (env == null)
        return null;
    JCClassDecl classNode = env.enclClass;
    if (classNode != null) {
        if (TreeInfo.symbolFor(classNode) == element)
            return classNode;
        for (JCTree node : classNode.getMembers())
            if (TreeInfo.symbolFor(node) == element)
                return node;
    }
    return null;
}
 
Example #7
Source File: OneToManyImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public OneToManyImpl(final AnnotationModelHelper helper, final Element element, AnnotationMirror oneToManyAnnotation, String name, Map<String, ? extends AnnotationMirror> annByType) {
    this.name = name;
    AnnotationParser parser = AnnotationParser.create(helper);
    parser.expectClass("targetEntity", new DefaultProvider() { // NOI18N
        public Object getDefaultValue() {
            return EntityMappingsUtilities.getCollectionArgumentTypeName(helper, element);
        }
    });
    parser.expectEnumConstantArray("cascade", helper.resolveType("javax.persistence.CascadeType"), new ArrayValueHandler() { // NOI18N
        public Object handleArray(List<AnnotationValue> arrayMembers) {
            return new CascadeTypeImpl(arrayMembers);
        }
    }, parser.defaultValue(new CascadeTypeImpl()));
    parser.expectEnumConstant("fetch", helper.resolveType("javax.persistence.FetchType"), parser.defaultValue("LAZY")); // NOI18N
    parser.expectString("mappedBy", parser.defaultValue("")); // NOI18N
    parseResult = parser.parse(oneToManyAnnotation);

    joinTable = new JoinTableImpl(helper, annByType.get("javax.persistence.JoinTable")); // NOI18N
    joinColumnList = EntityMappingsUtilities.getJoinColumns(helper, annByType);
}
 
Example #8
Source File: ConstructorBuilder.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Construct a new ConstructorBuilder.
 *
 * @param context  the build context.
 * @param typeElement the class whoses members are being documented.
 * @param writer the doclet specific writer.
 */
private ConstructorBuilder(Context context,
        TypeElement typeElement,
        ConstructorWriter writer) {
    super(context);
    this.typeElement = typeElement;
    this.writer = writer;
    visibleMemberMap = configuration.getVisibleMemberMap(typeElement,
            VisibleMemberMap.Kind.CONSTRUCTORS);
    constructors = visibleMemberMap.getMembers(typeElement);
    for (Element ctor : constructors) {
        if (utils.isProtected(ctor) || utils.isPrivate(ctor)) {
            writer.setFoundNonPubConstructor(true);
        }
    }
}
 
Example #9
Source File: AbstractObjectProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static List<Element> getAnnotatedMembers( final String annotationName,
        final AnnotationModelHelper helper )
{
    final List<Element> result = new LinkedList<Element>();
    try {
        helper.getAnnotationScanner().findAnnotations(
                annotationName, 
                EnumSet.of(ElementKind.FIELD, ElementKind.METHOD), 
                new AnnotationHandler() {
                        @Override
                        public void handleAnnotation(TypeElement type, 
                                Element element, AnnotationMirror annotation) 
                        {
                            result.add(element);
                        }
        });
    }
    catch (InterruptedException e) {
        FieldInjectionPointLogic.LOGGER.warning("Finding annotation "+
                annotationName+" was interrupted"); // NOI18N
    }
    return result;
}
 
Example #10
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 #11
Source File: BasicAnnotationProcessor.java    From auto with Apache License 2.0 6 votes vote down vote up
/**
 * Adds {@code element} and its enclosed elements to {@code annotatedElements} if they are
 * annotated with any annotations in {@code annotationTypes}. Does not traverse to member types of
 * {@code element}, so that if {@code Outer} is passed in the example below, looking for
 * {@code @X}, then {@code Outer}, {@code Outer.foo}, and {@code Outer.foo()} will be added to the
 * multimap, but neither {@code Inner} nor its members will.
 *
 * <pre><code>
 *   {@literal @}X class Outer {
 *     {@literal @}X Object foo;
 *     {@literal @}X void foo() {}
 *     {@literal @}X static class Inner {
 *       {@literal @}X Object bar;
 *       {@literal @}X void bar() {}
 *     }
 *   }
 * </code></pre>
 */
private static void findAnnotatedElements(
    Element element,
    ImmutableSet<TypeElement> annotationTypes,
    ImmutableSetMultimap.Builder<TypeElement, Element> annotatedElements) {
  for (Element enclosedElement : element.getEnclosedElements()) {
    if (!enclosedElement.getKind().isClass() && !enclosedElement.getKind().isInterface()) {
      findAnnotatedElements(enclosedElement, annotationTypes, annotatedElements);
    }
  }

  // element.getEnclosedElements() does NOT return parameter elements
  if (element instanceof ExecutableElement) {
    for (Element parameterElement : asExecutable(element).getParameters()) {
      findAnnotatedElements(parameterElement, annotationTypes, annotatedElements);
    }
  }
  for (TypeElement annotationType : annotationTypes) {
    if (isAnnotationPresent(element, annotationType)) {
      annotatedElements.put(annotationType, element);
    }
  }
}
 
Example #12
Source File: AddParameterOrLocalFix.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void resolveResourceVariable(final WorkingCopy wc, TreePath tp, TreeMaker make, TypeMirror proposedType) {
    final String name = ((IdentifierTree) tp.getLeaf()).getName().toString();

    final Element el = wc.getTrees().getElement(tp);
    if (el == null) {
        return;
    }

    if (tp.getParentPath().getLeaf().getKind() != Kind.ASSIGNMENT) {
        //?
        return ;
    }

    AssignmentTree at = (AssignmentTree) tp.getParentPath().getLeaf();
    VariableTree vt = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), name, make.Type(proposedType), at.getExpression());

    wc.rewrite(at, vt);
}
 
Example #13
Source File: ProcessorImpl.java    From takari-lifecycle with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
  for (Element element : roundEnv.getElementsAnnotatedWith(Annotation.class)) {
    try {
      TypeElement cls = (TypeElement) element;
      PackageElement pkg = (PackageElement) cls.getEnclosingElement();
      String clsSimpleName = getGeneratedClassName(cls, prefix);
      String pkgName = pkg.getQualifiedName().toString();
      FileObject sourceFile = createFile(pkgName, clsSimpleName, element);
      BufferedWriter w = new BufferedWriter(sourceFile.openWriter());
      try {
        w.append("package ").append(pkgName).append(";");
        w.newLine();
        appendClassAnnotations(w);
        w.append("public class ").append(clsSimpleName);
        appendBody(pkgName, clsSimpleName, w);
      } finally {
        w.close();
      }
    } catch (IOException e) {
      e.printStackTrace();
      processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage(), element);
    }
  }
  return false; // not "claimed" so multiple processors can be tested
}
 
Example #14
Source File: BaseModelAttributeInfo.java    From epoxy with Apache License 2.0 6 votes vote down vote up
/**
 * Check if the given class or any of its super classes have a super method with the given name.
 * Private methods are ignored since the generated subclass can't call super on those.
 */
protected boolean hasSuperMethod(TypeElement classElement, Element attribute) {
  if (!Utils.isEpoxyModel(classElement.asType())) {
    return false;
  }

  for (Element subElement : SynchronizationKt.getEnclosedElementsThreadSafe(classElement)) {
    if (subElement.getKind() == ElementKind.METHOD) {
      ExecutableElement method = (ExecutableElement) subElement;
      List<VariableElement> parameters = SynchronizationKt.getParametersThreadSafe(method);
      if (!method.getModifiers().contains(Modifier.PRIVATE)
          && method.getSimpleName().toString().equals(attribute.getSimpleName().toString())
          && parameters.size() == 1
          && parameters.get(0).asType().equals(attribute.asType())) {
        return true;
      }
    }
  }

  Element superClass = KotlinUtilsKt.superClassElement(classElement, typeUtils);
  return (superClass instanceof TypeElement)
      && hasSuperMethod((TypeElement) superClass, attribute);
}
 
Example #15
Source File: ReferenceTransformer.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public ReferenceTransformer(WorkingCopy info, ElementKind kind, 
        MemberSearchResult result, String name, Element target) {
    this.kind = kind;
    this.name = name;
    this.copy = info;
    this.target = target;
    if (result != null) {
        ElementHandle<? extends Element> s = result.getShadowed();
        if (s == null) {
            s = result.getOverriden();
        }
        if (s != null) {
            this.shadowed = s.resolve(info);
        }
        s = result.getShadowedGate();
        if (s != null) {
            this.shadowedGate = result.getShadowedGate().resolve(info);
        }
    }
}
 
Example #16
Source File: SourceAnalyzerFactory.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
@CheckForNull
public Void visitMethod(@NonNull final MethodTree node, @NonNull final Map<Pair<BinaryName,String>, UsagesData<String>> p) {
    Element old = enclosingElement;
    try {
        enclosingElement = ((JCTree.JCMethodDecl) node).sym;
        if (enclosingElement != null && enclosingElement.getKind() == ElementKind.METHOD) {
            mainMethod |= SourceUtils.isMainMethod((ExecutableElement) enclosingElement);
            // do not add idents for constructors, they always match their class' name, which is added as an ident separately
            addIdent(activeClass.peek(), node.getName(), p, true);
        }
        return super.visitMethod(node, p);
    } finally {
        enclosingElement = old;
    }
}
 
Example #17
Source File: IndexElement.java    From sqlitemagic with Apache License 2.0 5 votes vote down vote up
@Nullable
private static TypeElement getTableTypeElement(boolean composite, Element indexElement) {
  if (composite) {
    return (TypeElement) indexElement;
  } else {
    final Element enclosingElement = indexElement.getEnclosingElement();
    if (enclosingElement != null && enclosingElement instanceof TypeElement) {
      return (TypeElement) enclosingElement;
    }
  }
  return null;
}
 
Example #18
Source File: SqlBuilderHelper.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * Iterate over methods.
 *
 * @param typeElement
 *            the type element
 * @param listener
 *            the listener
 */
public static void forEachMethods(TypeElement typeElement, MethodFoundListener listener) {
	Elements elementUtils = BaseProcessor.elementUtils;
	List<? extends Element> list = elementUtils.getAllMembers(typeElement);

	for (Element item : list) {
		if (item.getKind() == ElementKind.METHOD) {
			listener.onMethod((ExecutableElement) item);
		}
	}
}
 
Example #19
Source File: AnnotatedMixinElementHandler.java    From Mixin with MIT License 5 votes vote down vote up
private void printMessage(Kind kind, String msg, Element e, AnnotationHandle annotation, SuppressedBy suppressedBy) {
    if (annotation == null) {
        this.ap.printMessage(kind, msg, e, suppressedBy);
    } else {
        this.ap.printMessage(kind, msg, e, annotation.asMirror(), suppressedBy);
    }
}
 
Example #20
Source File: WitchException.java    From Witch-Android with Apache License 2.0 5 votes vote down vote up
public static WitchException bindMethodWithIdMissingView(Element bind) {
    return new WitchException(
            String.format(
                    "%s%s has id declared in annotation but takes no view.\n" +
                            "Example usage:\n" +
                            "@Bind(id = R.id.title)\n" +
                            "void bind(TextView title)\n" +
                            readMore
                    , errorForElementParent(bind)
                    , methodWithReturnType(bind)
                    , describeBindAnnotations())
    );
}
 
Example #21
Source File: WebBeansAnalysisTask.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void analyzeType(TypeElement typeElement , TypeElement parent ,
        WebBeansModel model , CompilationInfo info )
{
    ElementKind kind = typeElement.getKind();
    ModelAnalyzer analyzer = ANALIZERS.get( kind );
    if ( analyzer != null ){
        analyzer.analyze(typeElement, parent, model, getCancel(), getResult());
    }
    if ( isCancelled() ){
        return;
    }
    List<? extends Element> enclosedElements = typeElement.getEnclosedElements();
    List<TypeElement> types = ElementFilter.typesIn(enclosedElements);
    for (TypeElement innerType : types) {
        if ( innerType == null ){
            continue;
        }
        analyzeType(innerType, typeElement , model , info );
    }
    Set<Element> enclosedSet = new HashSet<Element>( enclosedElements );
    enclosedSet.removeAll( types );
    for(Element element : enclosedSet ){
        if ( element == null ){
            continue;
        }
        analyze(typeElement, model, element, info );
    }
}
 
Example #22
Source File: CommonAnnotationHelper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void addServiceReference(final List<ServiceRef> serviceRefs, final Element element, TypeElement parentElement, final AnnotationModelHelper helper) {
    TypeMirror fieldTypeMirror = element.asType();
    if (fieldTypeMirror.getKind() == TypeKind.DECLARED) {
        DeclaredType fieldDeclaredType = (DeclaredType) fieldTypeMirror;
        Element fieldTypeElement = fieldDeclaredType.asElement();
        
        if (ElementKind.INTERFACE == fieldTypeElement.getKind() || ElementKind.CLASS == fieldTypeElement.getKind() ) {
            TypeElement typeElement = (TypeElement) fieldTypeElement;
            ServiceRef newServiceRef = new ServiceRefImpl(element, typeElement, parentElement, helper);
            // test if already exists
            ServiceRef existingServiceRef = null;
            for (ServiceRef sr : serviceRefs) {
                if (newServiceRef.getServiceRefName().equals(sr.getServiceRefName())) {
                    existingServiceRef = sr;
                }
            }
            if (existingServiceRef != null) {
                if (newServiceRef.sizePortComponentRef() > 0) {
                    PortComponentRef newPortComp = newServiceRef.getPortComponentRef(0);
                    // eventiually add new PortComponentRef
                    PortComponentRef[] portComps = existingServiceRef.getPortComponentRef();
                    boolean foundPortComponent = false;
                    for (PortComponentRef portComp : portComps) {
                        if (portComp.getServiceEndpointInterface().equals(newPortComp.getServiceEndpointInterface())) {
                            foundPortComponent = true;
                        }
                    }
                    if (!foundPortComponent) {
                        existingServiceRef.addPortComponentRef(newPortComp);
                    }
                }
            } else {
                serviceRefs.add(newServiceRef);
            }
        }
    }
}
 
Example #23
Source File: PhpTestingRegistrationProcessor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean handleProcess(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) throws LayerGenerationException {
    for (Element element : roundEnv.getElementsAnnotatedWith(PhpTestingProvider.Registration.class)) {
        layer(element)
                .instanceFile(PhpTesting.TESTING_PATH, null, PhpTestingProvider.class)
                .intvalue("position", element.getAnnotation(PhpTestingProvider.Registration.class).position()) // NOI18N
                .write();
    }
    return true;
}
 
Example #24
Source File: AdapterDescriptor.java    From paperparcel with Apache License 2.0 5 votes vote down vote up
private VariableElement getField(TypeElement element, String fieldName) {
  List<? extends Element> enclosedElements = element.getEnclosedElements();
  for (Element enclosedElement : enclosedElements) {
    if (enclosedElement instanceof VariableElement
        && enclosedElement.getSimpleName().contentEquals(fieldName)) {
      return (VariableElement) enclosedElement;
    }
  }
  throw new IllegalArgumentException(
      "No field found in " + element.getQualifiedName().toString() + " named " + fieldName);
}
 
Example #25
Source File: TestJavacTaskScanner.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
void testParseType(TypeElement clazz) {
    DeclaredType type = (DeclaredType)task.parseType("List<String>", clazz);
    for (Element member : elements.getAllMembers((TypeElement)type.asElement())) {
        TypeMirror mt = types.asMemberOf(type, member);
        System.out.format("type#%d: %s : %s -> %s%n",
            numParseTypeElements, member.getSimpleName(), member.asType(), mt);
        numParseTypeElements++;
    }
}
 
Example #26
Source File: ApNavigator.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public VariableElement[] getEnumConstants(TypeElement clazz) {
    List<? extends Element> elements = env.getElementUtils().getAllMembers(clazz);
    Collection<VariableElement> constants = new HashSet<VariableElement>();
    for (Element element : elements) {
        if (element.getKind().equals(ElementKind.ENUM_CONSTANT)) {
            constants.add((VariableElement) element);
        }
    }
    return constants.toArray(new VariableElement[constants.size()]);
}
 
Example #27
Source File: RenameTestClassRefactoringPlugin.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void addIfMatchMethod(final LocationResult location, final TestLocator testLocator, final List<RenameRefactoring> renameRefactoringsList) {
       if(location.getFileObject() != null && testLocator.getFileType(location.getFileObject()).equals(TestLocator.FileType.TEST)) {
    try {
	JavaSource.forFileObject(location.getFileObject()).runUserActionTask(new Task<CompilationController>() {
	    @Override
	    public void run(CompilationController javac) throws Exception {
		javac.toPhase(JavaSource.Phase.RESOLVED);
		final Element methodElement = treePathHandle.resolveElement(javac);
		String methodName = methodElement.getSimpleName().toString();
		String testMethodName = RefactoringUtils.getTestMethodName(methodName);
		CompilationUnitTree cut = javac.getCompilationUnit();
		Tree classTree = cut.getTypeDecls().get(0);
		List<? extends Tree> members = ((ClassTree) classTree).getMembers();
		for (int i = 0; i < members.size(); i++) {
                           Tree member = members.get(i);
                           if(member.getKind() != Tree.Kind.METHOD) {
                               continue;
                           }
                           MethodTree methodTree = (MethodTree) member;
		    if (methodTree.getName().contentEquals(testMethodName)
                                   && methodTree.getReturnType().getKind() == Tree.Kind.PRIMITIVE_TYPE
                                   && ((PrimitiveTypeTree) methodTree.getReturnType()).getPrimitiveTypeKind() == TypeKind.VOID) {
                                // test method should at least be void
                               classTree = ((ClassTree) classTree).getMembers().get(i);
                               TreePath tp = TreePath.getPath(cut, classTree);
                               RenameRefactoring renameRefactoring = new RenameRefactoring(Lookups.singleton(TreePathHandle.create(tp, javac)));
                               renameRefactoring.setNewName(RefactoringUtils.getTestMethodName(refactoring.getNewName()));
                               renameRefactoring.setSearchInComments(true);
                               renameRefactoringsList.add(renameRefactoring);
                               break;
                           }
		}
	    }
	}, true);
    } catch (IOException ex) {
	Exceptions.printStackTrace(ex);
    }
}
   }
 
Example #28
Source File: ScanStatement.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitVariable(VariableTree node, Void p) {
    Element e = info.getTrees().getElement(getCurrentPath());
    if (e != null && IntroduceHint.LOCAL_VARIABLES.contains(e.getKind())) {
        switch (phase) {
            case PHASE_BEFORE_SELECTION:
                localVariables.add((VariableElement) e);
                break;
            case PHASE_INSIDE_SELECTION:
                selectionLocalVariables.add((VariableElement) e);
                break;
        }
    }
    return super.visitVariable(node, p);
}
 
Example #29
Source File: ToothpickProcessor.java    From toothpick with Apache License 2.0 5 votes vote down vote up
protected boolean isNonStaticInnerClass(TypeElement typeElement) {
  Element outerClassOrPackage = typeElement.getEnclosingElement();
  if (outerClassOrPackage.getKind() != ElementKind.PACKAGE
      && !typeElement.getModifiers().contains(Modifier.STATIC)) {
    error(
        typeElement,
        "Class %s is a non static inner class. @Inject constructors are not allowed in non static inner classes.",
        typeElement.getQualifiedName());
    return true;
  }
  return false;
}
 
Example #30
Source File: CursorHelperGenerator.java    From RxAndroidOrm with Apache License 2.0 5 votes vote down vote up
public CursorHelperGenerator(Element element) {
    this.element = element;
    this.objectName = ProcessUtils.getObjectName(element);
    this.modelType = TypeName.get(element.asType());
    this.fields = ProcessUtils.getPrimitiveFields(element);
    this.otherClassFields = ProcessUtils.getNonPrimitiveClassFields(element);
    this.collections = ProcessUtils.getCollectionsOfPrimitiveFields(element);
}