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

The following examples show how to use javax.lang.model.element.Element#getSimpleName() . 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: UnusedImports.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void handleUnresolvableImports(Element decl,
        boolean methodInvocation, boolean removeStarImports) {
    Name simpleName = decl.getSimpleName();
    if (simpleName != null) {
        Collection<ImportTree> imps = simpleName2UnresolvableImports.get(simpleName.toString());

        if (imps != null) {
            for (ImportTree imp : imps) {
                if (!methodInvocation || imp.isStatic()) {
                    import2Highlight.remove(imp);
                }
            }
        } else {
            if (removeStarImports) {
                //TODO: explain
                for (ImportTree unresolvable : unresolvablePackageImports) {
                    if (!methodInvocation || unresolvable.isStatic()) {
                        import2Highlight.remove(unresolvable);
                    }
                }
            }
        }
    }
}
 
Example 2
Source File: FitProcessor.java    From fit with Apache License 2.0 6 votes vote down vote up
private boolean isSetter(Element method) {
  Name methodName = method.getSimpleName();
  if (!methodName.toString().startsWith("set")) {
    return false;
  }
  ExecutableType type = (ExecutableType) method.asType();
  //返回值不为void
  if (!TypeKind.VOID.equals(type.getReturnType().getKind())) {
    return false;
  }
  //有1个参数
  if (type.getParameterTypes().size() != 1) {
    return false;
  }

  if (methodName.length() < 4) {
    return false;
  }
  return true;
}
 
Example 3
Source File: MementoProcessor.java    From memento with Apache License 2.0 6 votes vote down vote up
private void generateMemento(Set<? extends Element> elements, Element hostActivity, TypeElement activityType)
        throws IOException {
    PackageElement packageElement = processingEnv.getElementUtils().getPackageOf(hostActivity);
    final String simpleClassName = hostActivity.getSimpleName() + "$Memento";
    final String qualifiedClassName = packageElement.getQualifiedName() + "." + simpleClassName;

    log("writing class " + qualifiedClassName);
    JavaFileObject sourceFile = processingEnv.getFiler().createSourceFile(
            qualifiedClassName, elements.toArray(new Element[elements.size()]));

    JavaWriter writer = new JavaWriter(sourceFile.openWriter());

    emitClassHeader(packageElement, activityType, writer);

    writer.beginType(qualifiedClassName, "class", EnumSet.of(Modifier.PUBLIC, Modifier.FINAL),
            "Fragment", LIB_PACKAGE + ".MementoMethods");

    emitFields(elements, writer);
    emitConstructor(simpleClassName, writer);
    emitReaderMethod(elements, hostActivity, writer);
    emitWriterMethod(elements, hostActivity, writer);

    writer.endType();
    writer.close();
}
 
Example 4
Source File: FitProcessor.java    From fit with Apache License 2.0 6 votes vote down vote up
private boolean isGetter(Element method) {
  Name methodName = method.getSimpleName();
  if ((!methodName.toString().startsWith("get")) && !methodName.toString().startsWith("is")) {
    return false;
  }
  ExecutableType type = (ExecutableType) method.asType();
  //返回值为void
  if (TypeKind.VOID.equals(type.getReturnType().getKind())) {
    return false;
  }
  //有参数
  if (type.getParameterTypes().size() > 0) {
    return false;
  }

  if (methodName.length() < 4) {
    return false;
  }
  return true;
}
 
Example 5
Source File: InfoTaglet.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public String toString(List<? extends DocTree> tags, Element element) {
    // The content lines below are primarily to help verify the element
    // and the values passed to init.
    return "<dt>"
            +"<span class=\"simpleTagLabel\">Info:</span>\n"
            + "</dt>"
            + "<dd>"
            + "<ul>\n"
            + "<li>Element: " + element.getKind() + " " + element.getSimpleName() + "\n"
            + "<li>Element supertypes: " +
                    env.getTypeUtils().directSupertypes(element.asType()) + "\n"
            + "<li>Doclet: " + doclet.getClass() + "\n"
            + "</ul>\n"
            + "</dd>";
}
 
Example 6
Source File: AuthorProcessor.java    From java-tutorial with Apache License 2.0 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
    for (Element elem : roundEnvironment.getElementsAnnotatedWith(Author.class)) {
        Author author = elem.getAnnotation(Author.class);
        String message = "annotation found in " + elem.getSimpleName()
                + " with author " + author;
        processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, message);
    }
    return false; // no further processing of this annotation type
}
 
Example 7
Source File: Checker.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private void checkParamsDocumented(List<? extends Element> list) {
    if (foundInheritDoc)
        return;

    for (Element e: list) {
        if (!foundParams.contains(e)) {
            CharSequence paramName = (e.getKind() == ElementKind.TYPE_PARAMETER)
                    ? "<" + e.getSimpleName() + ">"
                    : e.getSimpleName();
            reportMissing("dc.missing.param", paramName);
        }
    }
}
 
Example 8
Source File: PluginGenerator.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static void createPluginFactory(ProcessingEnvironment env, Element topLevelClass, List<GeneratedPlugin> plugins) {
    PackageElement pkg = (PackageElement) topLevelClass.getEnclosingElement();

    String genClassName = "PluginFactory_" + topLevelClass.getSimpleName();

    try {
        JavaFileObject factory = env.getFiler().createSourceFile(pkg.getQualifiedName() + "." + genClassName, topLevelClass);
        try (PrintWriter out = new PrintWriter(factory.openWriter())) {
            out.printf("// CheckStyle: stop header check\n");
            out.printf("// CheckStyle: stop line length check\n");
            out.printf("// GENERATED CONTENT - DO NOT EDIT\n");
            out.printf("// GENERATORS: %s, %s\n", VerifierAnnotationProcessor.class.getName(), PluginGenerator.class.getName());
            out.printf("package %s;\n", pkg.getQualifiedName());
            out.printf("\n");
            createImports(out, plugins);
            out.printf("\n");
            out.printf("@ServiceProvider(NodeIntrinsicPluginFactory.class)\n");
            out.printf("public class %s implements NodeIntrinsicPluginFactory {\n", genClassName);
            for (GeneratedPlugin plugin : plugins) {
                out.printf("\n");
                plugin.generate(env, out);
            }
            out.printf("\n");
            createPluginFactoryMethod(out, plugins);
            out.printf("}\n");
        }
    } catch (IOException e) {
        env.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage());
    }
}
 
Example 9
Source File: JSONRegistrationProcessor.java    From domino-jackson with Apache License 2.0 5 votes vote down vote up
private CodeBlock registerLine(Element element, String mapName) {
    String className = enclosingName(element) + (useInterface(element) ? element.getSimpleName() : "Mapper") + "Impl";
    String packageName = elementUtils.getPackageOf(element).getQualifiedName().toString();

    CodeBlock.Builder typeTokenBuilder = CodeBlock.builder();
    addTypeTokenLiteral(typeTokenBuilder, TypeName.get(getBeanType(element)));
    
    return CodeBlock.builder()
            .addStatement(
            	mapName + ".put($L, new " + packageName + "." + className + "())",
            	typeTokenBuilder.build())
            .build();
}
 
Example 10
Source File: JavadocHelper.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private String elementSignature(Element el) {
    switch (el.getKind()) {
        case ANNOTATION_TYPE: case CLASS: case ENUM: case INTERFACE:
            return ((TypeElement) el).getQualifiedName().toString();
        case FIELD:
            return elementSignature(el.getEnclosingElement()) + "." + el.getSimpleName() + ":" + el.asType();
        case ENUM_CONSTANT:
            return elementSignature(el.getEnclosingElement()) + "." + el.getSimpleName();
        case EXCEPTION_PARAMETER: case LOCAL_VARIABLE: case PARAMETER: case RESOURCE_VARIABLE:
            return el.getSimpleName() + ":" + el.asType();
        case CONSTRUCTOR: case METHOD:
            StringBuilder header = new StringBuilder();
            header.append(elementSignature(el.getEnclosingElement()));
            if (el.getKind() == ElementKind.METHOD) {
                header.append(".");
                header.append(el.getSimpleName());
            }
            header.append("(");
            String sep = "";
            ExecutableElement method = (ExecutableElement) el;
            for (Iterator<? extends VariableElement> i = method.getParameters().iterator(); i.hasNext();) {
                VariableElement p = i.next();
                header.append(sep);
                header.append(p.asType());
                sep = ", ";
            }
            header.append(")");
            return header.toString();
       default:
            return el.toString();
    }
}
 
Example 11
Source File: TargetViewBinder.java    From Witch-Android with Apache License 2.0 5 votes vote down vote up
public ViewBinder.Builder getViewBinderForBind(Element bind) throws WitchException {
    if(viewBinders == null) {
        throw new WitchException("Target binder for target " + target.getSimpleName() + " not found");
    }
    for (ViewBinder.Builder binder: viewBinders) {
        if (binder.getBindElement().getSimpleName().equals(bind.getSimpleName())) {
            return binder;
        }
    }
    throw new WitchException("Target binder for target " + target.getSimpleName() + ", " + bind.getSimpleName() + " not found");
}
 
Example 12
Source File: NestedTypeVars.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
String toString(Element el) {
    switch (el.getKind()) {
        case METHOD:
            return toString(el.getEnclosingElement()) + "." + el.getSimpleName();
        case CLASS:
            return processingEnv.getElementUtils().getBinaryName((TypeElement) el).toString();
        case TYPE_PARAMETER:
            return toString(((TypeParameterElement) el).getGenericElement()) + "." + el.getSimpleName();
        default:
            throw new IllegalStateException("Unexpected element: " + el + "(" + el.getKind() + ")");
    }
}
 
Example 13
Source File: Flow.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private boolean isUndefinedVariable(Element e) {
    Name n = e.getSimpleName();
    return undefinedVariables.containsKey(n);
}
 
Example 14
Source File: CreateQualifier.java    From netbeans with Apache License 2.0 4 votes vote down vote up
protected List<Fix> analyze( CompilationInfo compilationInfo, int offset )
    throws IOException 
{
    TreePath errorPath = findUnresolvedElement(compilationInfo, offset);
    if ( !checkProject(compilationInfo) || errorPath == null) {
        return Collections.<Fix>emptyList();
    }

    if (compilationInfo.getElements().getTypeElement("java.lang.Object") == null) { // NOI18N
        // broken java platform
        return Collections.<Fix>emptyList();
    }
    
    Element element = compilationInfo.getTrees().getElement(errorPath);
    if ( element == null || element.getSimpleName() == null || 
            errorPath.getLeaf().getKind() != Kind.IDENTIFIER )
    {
        return Collections.<Fix>emptyList();
    }
    
    TreePath parentPath = errorPath.getParentPath();
    if ( parentPath.getLeaf().getKind() != Kind.ANNOTATION ){
        return Collections.<Fix>emptyList();
    }
    Element annotation = compilationInfo.getTrees().getElement(parentPath);
    TreePath path = parentPath;
    while (path != null ){
        Tree leaf = path.getLeaf();
        Kind leafKind = leaf.getKind();
        if ( TreeUtilities.CLASS_TREE_KINDS.contains(leafKind) ){
            Element clazz = compilationInfo.getTrees().getElement(path);
            if ( clazz != null && clazz.getKind() == ElementKind.CLASS )
            {
                return analyzeClass( compilationInfo , (TypeElement)clazz , 
                        annotation );
            }
        }
        else if ( leafKind == Kind.VARIABLE){
            Element var = compilationInfo.getTrees().getElement(path);
            if ( var == null ){
                return null;
            }
            Element parent = var.getEnclosingElement();
            if ( var.getKind() == ElementKind.FIELD && 
                    (parent instanceof TypeElement))
            {
                return analyzeField( compilationInfo , var , annotation ,
                        (TypeElement)parent);
            }
        }
        else if ( leafKind == Kind.METHOD ){
            Element method = compilationInfo.getTrees().getElement(path);
            if ( method != null && method.getKind() == ElementKind.METHOD){
                return analyzeMethodParameter( compilationInfo , 
                        (ExecutableElement)method , annotation );
            }
        }
        path = path.getParentPath();
    }
    
    return null;
}
 
Example 15
Source File: ElementUtil.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public static String getName(Element element) {
  // Always return qualified package names.
  Name name = element.getKind() == ElementKind.PACKAGE
      ? ((PackageElement) element).getQualifiedName() : element.getSimpleName();
  return name.toString();
}
 
Example 16
Source File: ClassAnnotationProcessor.java    From Study_Android_Demo with Apache License 2.0 4 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {

    for (TypeElement te : annotations) {
        for (Element e : roundEnv.getElementsAnnotatedWith(te)) {
            // 准备在gradle的控制台打印信息
            Messager messager = processingEnv.getMessager();
            // 打印
            messager.printMessage(Diagnostic.Kind.NOTE, "Printing: " + e.toString());//注: Printing: tv
            messager.printMessage(Diagnostic.Kind.NOTE, "Printing: " + e.getSimpleName());//注: Printing: tv
            messager.printMessage(Diagnostic.Kind.NOTE, "Printing: " + e.getEnclosingElement().toString());//注: Printing: com.realmo.customannoation.MainActivity

            // 获取注解
            ClassAnnotation annotation = e.getAnnotation(ClassAnnotation.class);

            // 获取元素名并将其首字母大写
            String name = e.getSimpleName().toString();
            char c = Character.toUpperCase(name.charAt(0));
            name = String.valueOf(c+name.substring(1));

            // 包裹注解元素的元素, 也就是其父元素, 比如注解了成员变量或者成员函数, 其上层就是该类
            Element enclosingElement = e.getEnclosingElement();
            // 获取父元素的全类名, 用来生成包名
            String enclosingQualifiedName;
            if(enclosingElement instanceof PackageElement){
                enclosingQualifiedName = ((PackageElement)enclosingElement).getQualifiedName().toString();
            }else {
                enclosingQualifiedName = ((TypeElement)enclosingElement).getQualifiedName().toString();
            }
            try {
                // 生成的包名
                String genaratePackageName = enclosingQualifiedName.substring(0, enclosingQualifiedName.lastIndexOf('.'));
                // 生成的类名
                String genarateClassName = PREFIX + enclosingElement.getSimpleName() + SUFFIX;

                // 创建Java文件
                JavaFileObject f = processingEnv.getFiler().createSourceFile(genarateClassName);
                // 在控制台输出文件路径
                messager.printMessage(Diagnostic.Kind.NOTE, "Printing: " + f.toUri());//注: Printing: file:/C:/Users/54363/Desktop/code/Demo/customannoation/build/generated/source/apt/debug/My_MainActivityAutoGenerate.java
                Writer w = f.openWriter();
                try {
                    PrintWriter pw = new PrintWriter(w);
                    pw.println("package " + genaratePackageName + ";");
                    pw.println("\npublic class " + genarateClassName + " { ");
                    pw.println("\n    /** auto class code */");
                    pw.println("    public static void print" + name + "() {");
                    pw.println("        // effect class: " + enclosingElement.toString());
                    pw.println("        System.out.println(\"code path: "+f.toUri()+"\");");
                    pw.println("        System.out.println(\"annotation element: "+e.toString()+"\");");
                    pw.println("        System.out.println(\"annotation value: "+annotation.value()+"\");");
                    pw.println("    }");
                    pw.println("}");
                    pw.flush();
                } finally {
                    w.close();
                }
            } catch (IOException x) {
                processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                        x.toString());
            }
        }
    }

    //该方法返回ture表示该注解已经被处理, 后续不会再有其他处理器处理; 返回false表示仍可被其他处理器处理.
    return true;
}
 
Example 17
Source File: ToPojo.java    From sundrio with Apache License 2.0 4 votes vote down vote up
private static String getDefaultValue(Property p) {
    Object value = p.getAttribute(DEFAULT_VALUE);
    String stringVal = value != null ? String.valueOf(value) : null;

    if (p.getTypeRef().getDimensions() > 0) {
        StringBuilder sb = new StringBuilder();
        if  (p.getTypeRef() instanceof PrimitiveRef)  {
            sb.append(((PrimitiveRef) p.getTypeRef()).getName());
        } else if (p.getTypeRef() instanceof ClassRef) {
            sb.append("new ").append(((ClassRef) p.getTypeRef()).getFullyQualifiedName());
        }
        for (int d = 0; d < p.getTypeRef().getDimensions(); d++)  {
            if (value == null || String.valueOf(value).isEmpty()) {
                sb.append("[0]");
            } else {
                sb.append("[]");
            }
        }
        return sb.toString();
    }
    if (Constants.STRING_REF.equals(p.getTypeRef()) && value != null && !String.valueOf(value).startsWith("\"")) {
        return "\"" + value + "\"";
    } else if (value instanceof Element)  {
        Element element = (Element) value;
        if (element.getKind() == ElementKind.ENUM_CONSTANT) {
          return  element.getEnclosingElement() + "." +element.getSimpleName();
        }
    } else if (stringVal != null && stringVal.startsWith("@"))  {
       String annotationFQCN = stringVal.substring(1);
       TypeDef annotationDef = DefinitionRepository.getRepository().getDefinition(annotationFQCN);
       if  (annotationDef != null) {
           TypeDef pojoDef = ClazzAs.POJO.apply(annotationDef);
           if (BuilderUtils.hasDefaultConstructor(pojoDef)) {
              return "new " + pojoDef.getFullyQualifiedName() + "()";
           }
       }
        return "null";
    } else if (stringVal == null && p.getTypeRef() instanceof PrimitiveRef) {
        if (((PrimitiveRef) p.getTypeRef()).getName().equals("boolean")) {
            return "false";
        } else {
            return "0";
        }
    }
    return stringVal;
}
 
Example 18
Source File: AnnotatedMethods.java    From FastAdapter with MIT License 4 votes vote down vote up
public ArrayList<AnnotatedClass> enclosingClasses() throws ClassNotFoundException {

    ArrayList<AnnotatedClass> lAnnotatedClasses = new ArrayList<>();

    //Builder 模式
    final Set<? extends Element> buildElements =
        mRoundEnvironment.getElementsAnnotatedWith(RecyclerItemLayoutId.class);

    for (final Element lElement : buildElements) {
      if (!Utils.isSubtypeOfType(lElement.asType(), Utils.TYPE_BASEHOLDER)) {
        throw new IllegalStateException(lElement.asType()
            + " The class of RecyclerItemLayoutId must extends FastBaseHolder");
      }

      List<? extends Element> elementList = lElement.getEnclosedElements();
      final AnnotatedClass lAnnotatedClass = new AnnotatedClass((TypeElement) lElement);

      for (Element item :
          elementList) {
        FastAttribute fastAttribute = item.getAnnotation(FastAttribute.class);
        if (item.getKind().isField() && fastAttribute != null) {

          //私有属性不支持
          if (item.getModifiers().contains(Modifier.PRIVATE)) {
            throw new IllegalStateException(
                item + " modifiers error, Private property is not supported");
          }

          TypeMirror resultType = item.asType();
          Name fieldName = item.getSimpleName();

          AnnotatedField annotatedField = new AnnotatedField();
          annotatedField.setName(fieldName.toString());
          annotatedField.setType(resultType);
          annotatedField.setmIsStaticField(item.getModifiers().contains(
              Modifier.STATIC));
          annotatedField.setAnnotationMirrors(item.getAnnotationMirrors());
          annotatedField.setFastAttribute(fastAttribute);

          lAnnotatedClass.addField(annotatedField);
        }
      }
      lAnnotatedClasses.add(lAnnotatedClass);
    }

    return lAnnotatedClasses;
  }
 
Example 19
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);
}
 
Example 20
Source File: StaticImport.java    From netbeans with Apache License 2.0 2 votes vote down vote up
/**
 * @param e
 * @return the FQN for an Element
 */
private static String getFqn(CompilationInfo info, Element e) {
    return info.getElementUtilities().getElementName(e.getEnclosingElement(), true) + "." + e.getSimpleName();
}