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

The following examples show how to use javax.lang.model.element.TypeElement#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: AnnotationProcessor.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
private void generateApiFor(TypeElement type) {
    String pkg = packageOf(type).getQualifiedName().toString();
    String apiTypeName = type.getSimpleName() + "Api";
    String schema = readSchema(type);
    if (schema == null)
        return;
    List<String> queries = Stream.of(type.getAnnotationsByType(GraphqlQuery.class))
            .map(GraphqlQuery::value)
            .collect(toList());

    Generator generator = new Generator(pkg, apiTypeName, schema, queries);

    try {
        generator.generateSourceFiles().forEach(this::writeJavaSource);
    } catch (Exception e) {
        StringBuilder messages = new StringBuilder();
        for (Throwable t = e; t != null; t = t.getCause())
            messages.append(t.getMessage());
        processingEnv.getMessager().printMessage(ERROR, messages.toString(), type);
    }
}
 
Example 2
Source File: ClassEntity.java    From RxPay with Apache License 2.0 6 votes vote down vote up
/**
 * @param elementUtils
 * @param typeUtils
 * @param element      current anntated class
 */
public ClassEntity(Elements elementUtils, Types typeUtils, TypeElement element) {
    elementWeakCache = new WeakReference<TypeElement>(element);
    this.classPackageName = elementUtils.getPackageOf(element).getQualifiedName().toString();
    this.modifierSet = element.getModifiers();
    this.className = element.toString();
    annotationMirrors = element.getAnnotationMirrors();
    this.classSimpleName = element.getSimpleName();
    this.classQualifiedName = element.getQualifiedName();
    if ("java.lang.Object".equals(element.getSuperclass().toString())){
        this.superclass = null;
    }else{
        this.superclass = element.getSuperclass().toString();
    }
    List<? extends TypeMirror> interfaces = element.getInterfaces();

    for (TypeMirror anInterface : interfaces){
        this.interfaces.add(typeUtils.asElement(anInterface).toString());
    }
}
 
Example 3
Source File: ElementDescription.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isAnonymous(Element el) {
    if (!el.getKind().isClass()) return false;
    
    TypeElement clazz = (TypeElement) el;

    return    clazz.getQualifiedName() == null
           || clazz.getQualifiedName().length() == 0
           || clazz.getSimpleName() == null
           || clazz.getSimpleName().length() == 0;
}
 
Example 4
Source File: InjectViewStateProcessor.java    From Moxy with MIT License 5 votes vote down vote up
private String getViewClassFromGeneric(TypeElement typeElement) {
	TypeMirror superclass = typeElement.asType();

	Map<String, String> parentTypes = Collections.emptyMap();

	if (!typeElement.getTypeParameters().isEmpty()) {
		MvpCompiler.getMessager().printMessage(Diagnostic.Kind.WARNING, "Your " + typeElement.getSimpleName() + " is typed. @InjectViewState may generate wrong code. Your can set view/view state class manually.");
	}

	while (superclass.getKind() != TypeKind.NONE) {
		TypeElement superclassElement = (TypeElement) ((DeclaredType) superclass).asElement();

		final List<? extends TypeMirror> typeArguments = ((DeclaredType) superclass).getTypeArguments();
		final List<? extends TypeParameterElement> typeParameters = superclassElement.getTypeParameters();

		if (typeArguments.size() > typeParameters.size()) {
			throw new IllegalArgumentException("Code generation for interface " + typeElement.getSimpleName() + " failed. Simplify your generics. (" + typeArguments + " vs " + typeParameters + ")");
		}

		Map<String, String> types = new HashMap<>();
		for (int i = 0; i < typeArguments.size(); i++) {
			types.put(typeParameters.get(i).toString(), fillGenerics(parentTypes, typeArguments.get(i)));
		}

		if (superclassElement.toString().equals(MVP_PRESENTER_CLASS)) {
			// MvpPresenter is typed only on View class
			return fillGenerics(parentTypes, typeArguments);
		}

		parentTypes = types;

		superclass = superclassElement.getSuperclass();
	}

	return "";
}
 
Example 5
Source File: MyAnnotationProcessor.java    From takari-lifecycle with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
  for (Element element : roundEnv.getElementsAnnotatedWith(MyAnnotation.class)) {
    try {
      TypeElement cls = (TypeElement) element;
      PackageElement pkg = (PackageElement) cls.getEnclosingElement();
      String clsSimpleName = "My" + cls.getSimpleName();
      String clsQualifiedName = pkg.getQualifiedName() + "." + clsSimpleName;
      JavaFileObject sourceFile =
          processingEnv.getFiler().createSourceFile(clsQualifiedName, element);
      OutputStream ios = sourceFile.openOutputStream();
      OutputStreamWriter writer = new OutputStreamWriter(ios, "UTF-8");
      BufferedWriter w = new BufferedWriter(writer);
      try {
        w.append("package ").append(pkg.getQualifiedName()).append(";");
        w.newLine();
        w.append("public class ").append(clsSimpleName).append(" { }");
      } finally {
        w.close();
        writer.close();
        ios.close();
      }
    } catch (IOException e) {
      e.printStackTrace();
    } 
  }
  return true;
}
 
Example 6
Source File: T6358786.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws IOException {
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    String srcdir = System.getProperty("test.src");
    File file = new File(srcdir, args[0]);
    JavacTaskImpl task = (JavacTaskImpl)tool.getTask(null, fm, null, null, null, fm.getJavaFileObjectsFromFiles(Arrays.asList(file)));
    Elements elements = task.getElements();
    for (TypeElement clazz : task.enter(task.parse())) {
        String doc = elements.getDocComment(clazz);
        if (doc == null)
            throw new AssertionError(clazz.getSimpleName() + ": no doc comment");
        System.out.format("%s: %s%n", clazz.getSimpleName(), doc);
    }
}
 
Example 7
Source File: T6358786.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws IOException {
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    String srcdir = System.getProperty("test.src");
    File file = new File(srcdir, args[0]);
    JavacTaskImpl task = (JavacTaskImpl)tool.getTask(null, fm, null, null, null, fm.getJavaFileObjectsFromFiles(Arrays.asList(file)));
    Elements elements = task.getElements();
    for (TypeElement clazz : task.enter(task.parse())) {
        String doc = elements.getDocComment(clazz);
        if (doc == null)
            throw new AssertionError(clazz.getSimpleName() + ": no doc comment");
        System.out.format("%s: %s%n", clazz.getSimpleName(), doc);
    }
}
 
Example 8
Source File: T6358786.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws IOException {
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    String srcdir = System.getProperty("test.src");
    File file = new File(srcdir, args[0]);
    JavacTaskImpl task = (JavacTaskImpl)tool.getTask(null, fm, null, null, null, fm.getJavaFileObjectsFromFiles(Arrays.asList(file)));
    Elements elements = task.getElements();
    for (TypeElement clazz : task.enter(task.parse())) {
        String doc = elements.getDocComment(clazz);
        if (doc == null)
            throw new AssertionError(clazz.getSimpleName() + ": no doc comment");
        System.out.format("%s: %s%n", clazz.getSimpleName(), doc);
    }
}
 
Example 9
Source File: ValueAttribute.java    From immutables with Apache License 2.0 5 votes vote down vote up
private @Nullable NullabilityAnnotationInfo isAccessorNullableAccessor(Element element) {
  for (AnnotationMirror annotation : element.getAnnotationMirrors()) {
    TypeElement annotationElement = (TypeElement) annotation.getAnnotationType().asElement();
    Name simpleName = annotationElement.getSimpleName();
    Name qualifiedName = annotationElement.getQualifiedName();
    if (isNullableAnnotation(simpleName, qualifiedName)) {
      return ImmutableNullabilityAnnotationInfo.of(annotationElement);
    }
  }
  return null;
}
 
Example 10
Source File: ElementSearch.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static TypeElement getInnerClass(Elements elements, String name) {
    int index = name.indexOf("$"); // NOI18N
    TypeElement typeElement = null;
    if (index > 0 && name.length() > index + 1) {
        TypeElement enclosingElement = elements.getTypeElement(name.substring(0, index));

        int nextIndex = index;
        while (enclosingElement != null && nextIndex >= 0) {
            String subName = name.substring(nextIndex + 1);
            int subIndex = subName.indexOf("$"); // NOI18N
            if (subIndex >= 0) {
                subName = subName.substring(0, subIndex);
                nextIndex = nextIndex + 1 + subIndex;
            } else {
                nextIndex = -1;
            }

            boolean found = false;
            for (TypeElement elem : ElementFilter.typesIn(enclosingElement.getEnclosedElements())) {
                Name elemName = elem.getSimpleName();

                if (elemName.toString().equals(subName)) {
                    enclosingElement = elem;
                    found = true;
                    break;
                }
            }

            if (!found) {
                enclosingElement = null;
            }
        }
        typeElement = enclosingElement;
    }
    return typeElement;
}
 
Example 11
Source File: ReplaceConstructorWithBuilderUI.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private ReplaceConstructorWithBuilderUI(TreePathHandle constructor, CompilationInfo info) {
    this.refactoring = new ReplaceConstructorWithBuilderRefactoring(constructor);
    ExecutableElement contructorElement = (ExecutableElement) constructor.resolveElement(info);
    this.name = contructorElement.getSimpleName().toString();
    MethodTree constTree = (MethodTree) constructor.resolve(info).getLeaf();
    paramaterNames = new ArrayList<String>();
    parameterTypes = new ArrayList<String>();
    parameterTypeVars = new ArrayList<Boolean>();
    boolean varargs = contructorElement.isVarArgs();
    List<? extends VariableElement> parameterElements = contructorElement.getParameters();
    List<? extends VariableTree> parameters = constTree.getParameters();
    for (int i = 0; i < parameters.size(); i++) {
        VariableTree var = parameters.get(i);
        paramaterNames.add(var.getName().toString());
        String type = contructorElement.getParameters().get(i).asType().toString();
        if(varargs && i+1 == parameters.size()) {
            if(var.getType().getKind() == Tree.Kind.ARRAY_TYPE) {
                ArrayTypeTree att = (ArrayTypeTree) var.getType();
                type = att.getType().toString();
                type += "..."; //NOI18N
            }
        }
        parameterTypes.add(type);
        parameterTypeVars.add(parameterElements.get(i).asType().getKind() == TypeKind.TYPEVAR);
    }
    TypeElement typeEl = (TypeElement) contructorElement.getEnclosingElement();
    if(typeEl.getNestingKind() != NestingKind.TOP_LEVEL) {
        PackageElement packageOf = info.getElements().getPackageOf(typeEl);
        builderFQN = packageOf.toString() + "." + typeEl.getSimpleName().toString();
    } else {
        builderFQN = typeEl.getQualifiedName().toString();
    }
    buildMethodName = "create" + typeEl.getSimpleName();
}
 
Example 12
Source File: T6358786.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws IOException {
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    String srcdir = System.getProperty("test.src");
    File file = new File(srcdir, args[0]);
    JavacTaskImpl task = (JavacTaskImpl)tool.getTask(null, fm, null, null, null, fm.getJavaFileObjectsFromFiles(Arrays.asList(file)));
    Elements elements = task.getElements();
    for (TypeElement clazz : task.enter(task.parse())) {
        String doc = elements.getDocComment(clazz);
        if (doc == null)
            throw new AssertionError(clazz.getSimpleName() + ": no doc comment");
        System.out.format("%s: %s%n", clazz.getSimpleName(), doc);
    }
}
 
Example 13
Source File: Processor.java    From immutables with Apache License 2.0 5 votes vote down vote up
private String getTemplateText(
    Filer filer,
    TypeElement templateType,
    PackageElement packageElement) throws IOException {
  CharSequence relativeName = templateType.getSimpleName() + ".generator";
  CharSequence packageName = packageElement.getQualifiedName();
  List<Exception> suppressed = Lists.newArrayList();
  try {
    return filer.getResource(StandardLocation.SOURCE_PATH, packageName, relativeName)
        .getCharContent(true)
        .toString();
  } catch (Exception cannotGetFromSourcePath) {
    suppressed.add(cannotGetFromSourcePath);
    try {
      return filer.getResource(StandardLocation.CLASS_OUTPUT, packageName, relativeName)
          .getCharContent(true)
          .toString();
    } catch (Exception cannotGetFromOutputPath) {
      suppressed.add(cannotGetFromOutputPath);
      try {
        return filer.getResource(StandardLocation.CLASS_PATH,
            "",
            packageName.toString().replace('.', '/') + '/' + relativeName)
            .getCharContent(true)
            .toString();
      } catch (IOException cannotGetFromClasspath) {
        for (Exception e : suppressed) {
          cannotGetFromClasspath.addSuppressed(e);
        }
        throw cannotGetFromClasspath;
      }
    }
  }
}
 
Example 14
Source File: T6358786.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws IOException {
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    String srcdir = System.getProperty("test.src");
    File file = new File(srcdir, args[0]);
    JavacTaskImpl task = (JavacTaskImpl)tool.getTask(null, fm, null, null, null, fm.getJavaFileObjectsFromFiles(Arrays.asList(file)));
    Elements elements = task.getElements();
    for (TypeElement clazz : task.enter(task.parse())) {
        String doc = elements.getDocComment(clazz);
        if (doc == null)
            throw new AssertionError(clazz.getSimpleName() + ": no doc comment");
        System.out.format("%s: %s%n", clazz.getSimpleName(), doc);
    }
}
 
Example 15
Source File: T6358786.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws IOException {
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    String srcdir = System.getProperty("test.src");
    File file = new File(srcdir, args[0]);
    JavacTaskImpl task = (JavacTaskImpl)tool.getTask(null, fm, null, null, null, fm.getJavaFileObjectsFromFiles(Arrays.asList(file)));
    Elements elements = task.getElements();
    for (TypeElement clazz : task.enter(task.parse())) {
        String doc = elements.getDocComment(clazz);
        if (doc == null)
            throw new AssertionError(clazz.getSimpleName() + ": no doc comment");
        System.out.format("%s: %s%n", clazz.getSimpleName(), doc);
    }
}
 
Example 16
Source File: GeneratedTypes.java    From immutables with Apache License 2.0 4 votes vote down vote up
public static final String getSimpleName(TypeElement type) {
  return GENERATOR_PREFIX + type.getSimpleName();
}
 
Example 17
Source File: ValueAttribute.java    From immutables with Apache License 2.0 4 votes vote down vote up
private void initSpecialAnnotations() {
  Environment environment = containingType.constitution.protoclass().environment();
  ImmutableList.Builder<AnnotationInjection> annotationInjections = null;

  for (AnnotationMirror annotation : element.getAnnotationMirrors()) {
    MetaAnnotated metaAnnotated = MetaAnnotated.from(annotation, environment);

    for (InjectionInfo info : metaAnnotated.injectAnnotation()) {
      if (annotationInjections == null) {
        annotationInjections = ImmutableList.builder();
      }
      annotationInjections.add(info.injectionFor(annotation, environment));
    }

    TypeElement annotationElement = (TypeElement) annotation.getAnnotationType().asElement();
    Name simpleName = annotationElement.getSimpleName();
    Name qualifiedName = annotationElement.getQualifiedName();
    if (isNullableAnnotation(simpleName, qualifiedName)) {
      nullability = ImmutableNullabilityAnnotationInfo.of(annotationElement);
    } else if (simpleName.contentEquals(TypeStringProvider.EPHEMERAL_ANNOTATION_ALLOW_NULLS)) {
      nullElements = NullElements.ALLOW;
    } else if (simpleName.contentEquals(TypeStringProvider.EPHEMERAL_ANNOTATION_SKIP_NULLS)) {
      nullElements = NullElements.SKIP;
    }
  }
  if (containingType.isGenerateJacksonProperties()
      && typeKind.isMap()
      && Proto.isAnnotatedWith(element, Annotations.JACKSON_ANY_GETTER)) {
    jacksonAnyGetter = true;
  }
  if (containingType.isGenerateJacksonMapped()
      && (isGenerateAbstract || isGenerateDefault)
      && Proto.isAnnotatedWith(element, Annotations.JACKSON_VALUE)) {
    jacksonValue = true;
  }
  if (isCollectionType()
      && nullElements == NullElements.BAN
      && protoclass().styles().style().validationMethod() == ValidationMethod.NONE) {
    nullElements = NullElements.NOP;
  }
  if (annotationInjections != null) {
    this.annotationInjections = annotationInjections.build();
  }
}
 
Example 18
Source File: NoPackageNameException.java    From Aurora with Apache License 2.0 4 votes vote down vote up
public NoPackageNameException(TypeElement typeElement) {
    super("The package of " + typeElement.getSimpleName() + " has no name");
}
 
Example 19
Source File: EnumsProviderClassBuilder.java    From aircon with MIT License 4 votes vote down vote up
private MethodSpec createEnumProviderMethod(final TypeElement enumClass, final List<VariableElement> consts) {
	final String methodName = Consts.GETTER_METHOD_PREFIX + enumClass.getSimpleName();
	final MethodSpec.Builder builder = MethodSpec.methodBuilder(methodName)
	                                             .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
	                                             .returns(TypeName.get(enumClass.asType()));

	final TypeName parameterType = getRemoteValueType(consts);
	builder.addParameter(parameterType, PARAMETER_VALUE, Modifier.FINAL);
	builder.addParameter(parameterType, PARAMETER_DEFAULT_VALUE, Modifier.FINAL);

	final CodeBlockBuilder bodyCodeBuilder = new CodeBlockBuilder();
	final boolean checkNull = !parameterType.isPrimitive();
	if (checkNull) {
		bodyCodeBuilder.beginIf(new CodeBlockBuilder().addBinaryOperator(CodeBlockBuilder.OPERATOR_UNEQUALITY, PARAMETER_VALUE, null)
		                                              .build());
	}
	bodyCodeBuilder.beginSwitch(PARAMETER_VALUE);

	for (VariableElement variableElement : consts) {
		final CodeBlock enumConst = new CodeBlockBuilder().addClassQualifier(TypeName.get(enumClass.asType()))
		                                                  .add(variableElement.getSimpleName())
		                                                  .build();
		bodyCodeBuilder.addSwitchCase(getRemoteValue(variableElement), new CodeBlockBuilder().addReturn(enumConst)
		                                                                                     .build());
	}

	bodyCodeBuilder.endSwitch();

	if (checkNull) {
		bodyCodeBuilder.endIf();
	}

	final CodeBlock condition = new CodeBlockBuilder().addBinaryOperator(CodeBlockBuilder.OPERATOR_UNEQUALITY, PARAMETER_VALUE, PARAMETER_DEFAULT_VALUE)
	                                                  .build();
	final CodeBlock recursiveCall = new CodeBlockBuilder().addMethodCall(methodName, PARAMETER_DEFAULT_VALUE, PARAMETER_DEFAULT_VALUE)
	                                                      .build();
	bodyCodeBuilder.addReturn(new CodeBlockBuilder().addConditionalExpression(condition, recursiveCall, null)
	                                                .build());
	return builder.addCode(bodyCodeBuilder.build())
	              .build();
}
 
Example 20
Source File: ProcessorImplLastRound.java    From takari-lifecycle with Eclipse Public License 1.0 4 votes vote down vote up
protected String getGeneratedClassName(TypeElement cls, String prefix) {
  return prefix + cls.getSimpleName();
}