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

The following are Jave code examples for showing how to use getSimpleName() of the javax.lang.model.element.TypeElement class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: RxPay   File: ClassEntity.java   View Source Code Vote up 6 votes
/**
 * @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 2
Project: AndroidKVO   File: KVOProcessor.java   View Source Code Vote up 6 votes
private AnnotatedClass buildAnnotatedClass(TypeElement annotatedClass) {

        List<VariableElement> fields = new ArrayList<>();

        for (Element element : annotatedClass.getEnclosedElements()) {

            if (!(element instanceof VariableElement)) {
                continue;
            }
            VariableElement variableElement = (VariableElement) element;

            if (variableElement.getAnnotation(KVOField.class) != null) {

                fields.add(variableElement);
            }
        }

        return new AnnotatedClass(annotatedClass.getSimpleName() + "KVO", fields, annotatedClass
                , processingEnv.getElementUtils().getPackageOf(annotatedClass).getQualifiedName().toString());
    }
 
Example 3
Project: DUnit   File: DUnitModelUtil.java   View Source Code Vote up 6 votes
/**
 * 获取TypeElement真实的类名
 */
public String getRealClassName(TypeElement typeElement) {
	NestingKind nestingKind = typeElement.getNestingKind();
	if (nestingKind.isNested()) {
		Element enclosingElement = typeElement.getEnclosingElement();
		if (enclosingElement.getKind() == ElementKind.CLASS || enclosingElement.getKind() == ElementKind.INTERFACE){
			String enclosingClassName = getRealClassName((TypeElement) enclosingElement);
			return enclosingClassName + "$" + typeElement.getSimpleName();
		}else {
			mErrorReporter.reportError("the type(" + enclosingElement.getKind()+ ") of enclosing element is not CLASS or INTERFACE.",typeElement);
			return null;
		}
	}else {
		return typeElement.getQualifiedName().toString();
	}
}
 
Example 4
Project: KiiAnnotation   File: KiiAnnotationProcessor.java   View Source Code Vote up 5 votes
private static String getRegularClassString(Class<? extends Annotation> cls, TypeElement typeElement) {
    if (cls.equals(ApplicationScope.class)) {
        ApplicationScope appBucketObject = typeElement.getAnnotation(ApplicationScope.class);
        return typeElement.getSimpleName() + appBucketObject.suffix();
    } else if (cls.equals(GroupScope.class)) {
        GroupScope groupBucketObject = typeElement.getAnnotation(GroupScope.class);
        return typeElement.getSimpleName() + groupBucketObject.suffix();
    } else if (cls.equals(UserScope.class)) {
        UserScope userBucketObject = typeElement.getAnnotation(UserScope.class);
        return typeElement.getSimpleName() + userBucketObject.suffix();
    } else {
        throw new IllegalAnnotationException();
    }
}
 
Example 5
Project: GitHub   File: ViewStateProviderClassGenerator.java   View Source Code Vote up 5 votes
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 6
Project: GitHub   File: Processor.java   View Source Code Vote up 5 votes
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 7
Project: GitHub   File: ValueAttribute.java   View Source Code Vote up 5 votes
private void initSpecialAnnotations() {
  for (AnnotationMirror annotation : element.getAnnotationMirrors()) {
    TypeElement annotationElement = (TypeElement) annotation.getAnnotationType().asElement();
    Name simpleName = annotationElement.getSimpleName();
    Name qualifiedName = annotationElement.getQualifiedName();
    if (qualifiedName.contentEquals(Annotations.JAVAX_CHECK_FOR_NULL)
        || qualifiedName.contentEquals(Annotations.JAVAX_NULLABLE)
        || simpleName.contentEquals(containingType.names().nullableAnnotation)) {
      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.ALLOW;
  }
}
 
Example 8
Project: FactoryAnnotation   File: FactoryGroupedClasses.java   View Source Code Vote up 5 votes
public void generateCode(Elements elementUtils, Filer filer) throws IOException {
    TypeElement superClassName = elementUtils.getTypeElement(qualifiedClassName);
    String factoryClassName = superClassName.getSimpleName() + SUFFIX;

    JavaFileObject jfo = filer.createSourceFile(qualifiedClassName + SUFFIX);
    Writer writer = jfo.openWriter();
    JavaWriter jw = new JavaWriter(writer);

    // 写包名
    PackageElement pkg = elementUtils.getPackageOf(superClassName);
    if (!pkg.isUnnamed()) {
        jw.emitPackage(pkg.getQualifiedName().toString());
        jw.emitEmptyLine();
    } else {
        jw.emitPackage("");
    }

    jw.beginType(factoryClassName, "class", EnumSet.of(Modifier.PUBLIC));
    jw.emitEmptyLine();
    jw.beginMethod(qualifiedClassName, "create", EnumSet.of(Modifier.PUBLIC), "String", "id");

    jw.beginControlFlow("if (id == null)");
    jw.emitStatement("throw new IllegalArgumentException(\"id is null!\")");
    jw.endControlFlow();

    for (FactoryAnnotatedClass item : itemsMap.values()) {
        jw.beginControlFlow(String.format("if (\"%s\".equals(id))", item.getId()));
        jw.emitStatement("return new %s()", item.getTypeElement().getQualifiedName().toString());
        jw.endControlFlow();
        jw.emitEmptyLine();
    }

    jw.emitStatement("throw new IllegalArgumentException(\"Unknown id = \" + id)");
    jw.endMethod();
    jw.endType();
    jw.close();
}
 
Example 9
Project: EgTest   File: ClassWriter.java   View Source Code Vote up 5 votes
private ClassWriter(CodeInjector codeInjector, TypeElement classElement, MessageHandler messageHandler, List<EgItem<?>> items) {
    this.codeInjector = codeInjector;
    this.messageHandler = messageHandler;
    this.items = items;
    this.classElement = JavaModelUtil.topLevelClass(items.get(0).getElement());
    this.className = classElement.getSimpleName() +"$EgTest";
}
 
Example 10
Project: shoebill   File: ShoebillProcessor.java   View Source Code Vote up 4 votes
private String getTargetClassName(TypeElement originalClass) {
    return originalClass.getSimpleName() + "Wrapper";
}
 
Example 11
Project: GeneratorX   File: NoPackageNameException.java   View Source Code Vote up 4 votes
public NoPackageNameException(TypeElement typeElement) {
    super("The package of " + typeElement.getSimpleName() + " has no name");
}
 
Example 12
Project: GitHub   File: PresenterBinderClassGenerator.java   View Source Code Vote up 4 votes
private static String generatePresenterBinderClass(final String builder, String targetClass, final Field field) {
	TypeElement clazz = (TypeElement) ((DeclaredType) field.getClazz()).asElement();
	String s = "\tpublic class " + field.getGeneratedClassName() + " extends PresenterField {\n" +
	           "\t\tpublic " + field.getGeneratedClassName() + "() {\n" +
	           "\t\t\tsuper(" + field.getTag() + ", PresenterType." + field.getType().name() + ", " + field.getPresenterId() + ", " + clazz + ".class);\n" +
	           "\t\t}\n" +
	           "\n" +
	           "\t\[email protected]\n" +
	           "\t\tpublic void bind(Object target, MvpPresenter presenter) {\n" +
	           "\t\t\t((" + targetClass + ") target)." + field.getName() + " = (" + clazz.getQualifiedName() + ") presenter;\n" +
	           "\t\t}\n";

		s += "\n" +
		     "\t\[email protected]\n" +
		     "\t\tpublic MvpPresenter<?> providePresenter(Object delegated) {\n";
	if (field.getPresenterProviderMethodName() != null) {
		s+= "\t\t\treturn ((" + targetClass + ") delegated)." + field.getPresenterProviderMethodName() + "();\n";
	} else {
		boolean hasEmptyConstructor = false;
		List<? extends Element> enclosedElements = clazz.getEnclosedElements();
		for (Element enclosedElement : enclosedElements) {
			if (enclosedElement.getKind() == ElementKind.CONSTRUCTOR) {
				List<? extends VariableElement> parameters = ((ExecutableElement) enclosedElement).getParameters();
				if (parameters == null || parameters.isEmpty()) {
					hasEmptyConstructor = true;
					break;
				}
			}
		}
		if (hasEmptyConstructor) {
		s += "\t\t\treturn new " + clazz.getQualifiedName() + "();\n";
		} else {
		s += "\t\t\tthrow new IllegalStateException(\"" + clazz.getSimpleName() + " has not default constructor. You can apply @ProvidePresenter to some method which will construct Presenter. Also you can make it default constructor\");\n";
		}
	}
	    s += "\t\t}\n";

	if (field.getPresenterTagProviderMethodName() != null) {
		s += "\n" +
		     "\t\[email protected]\n" +
		     "\t\tpublic String getTag(Object delegated) {\n" +
		     "\t\t\treturn String.valueOf(((" + targetClass + ") delegated)." + field.getPresenterTagProviderMethodName() + "());\n" +
		     "\t\t}\n";
	}

	s += "\t}\n" +
	     "\n";
	return builder + s;
}
 
Example 13
Project: GitHub   File: NoPackageNameException.java   View Source Code Vote up 4 votes
public NoPackageNameException(TypeElement typeElement) {
    super("The package of " + typeElement.getSimpleName() + " has no name");
}
 
Example 14
Project: GitHub   File: GeneratedTypes.java   View Source Code Vote up 4 votes
public static final String getSimpleName(TypeElement type) {
  return GENERATOR_PREFIX + type.getSimpleName();
}
 
Example 15
Project: autojackson   File: DeserializerCreator.java   View Source Code Vote up 4 votes
/**
 * Creates a custom Jackson deserializer for the given
 * {@link TypeElement}. Filling out the logic of the actual
 * deserialize method using the {@link DeserializerCreator
 * #implementDeserializeMethod(TypeElement, Builder)}
 * method implemented by our subclasses.
 *
 * @param typeElement The interface to create a custom deserializer for
 */
public void createDeserializer(TypeElement typeElement) {
    Name className = typeElement.getSimpleName();

    DeclaredType declaredType = this.typeUtils.getDeclaredType(typeElement);
    ClassName stdDeserializer = ClassName.get(StdDeserializer.class);
    TypeName deserializerType = TypeName.get(declaredType);
    ParameterizedTypeName parameterizedDeserializer = ParameterizedTypeName.get(stdDeserializer, deserializerType);

    MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC);
    // since Generics don't work when calling .class, check if there are type parameters
    if (typeElement.getTypeParameters().isEmpty()) {
        // if not we can use $T
        constructorBuilder.addStatement("super($T.class)", typeElement);
    } else {
        // if so, we need to use the fully qualified name and $L
        constructorBuilder.addStatement("super($L.class)", typeElement.getQualifiedName());
    }
    MethodSpec constructor = constructorBuilder.build();

    ParameterSpec jsonParserParameter = ParameterSpec.builder(JsonParser.class, JSON_PARSER_PARAMETER_NAME)
            .build();
    ParameterSpec deserializationContextParameter = ParameterSpec.builder(DeserializationContext.class, DESERIALIZATION_CONTEXT_PARAMETER_NAME)
            .build();

    MethodSpec.Builder deserializeMethodBuilder = MethodSpec.methodBuilder("deserialize")
            .addAnnotation(Override.class)
            .addParameter(jsonParserParameter)
            .addParameter(deserializationContextParameter)
            .addException(ClassName.get(IOException.class))
            .addException(ClassName.get(JsonProcessingException.class))
            .returns(TypeName.get(declaredType))
            .addModifiers(Modifier.PUBLIC);

    MethodSpec deserializeMethod = implementDeserializeMethod(typeElement, deserializeMethodBuilder);

    TypeSpec deserializationClass = TypeSpec
            .classBuilder(className + DESERIALIZER_CLASS_NAME_SUFFIX)
            .superclass(parameterizedDeserializer)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addMethod(constructor)
            .addMethod(deserializeMethod)
            .build();

    PackageElement packageElement = this.elementUtils.getPackageOf(typeElement);
    JavaFile javaFile = JavaFile
            .builder(packageElement.getQualifiedName().toString(), deserializationClass)
            .build();

    // and write that file to disc
    try {
        javaFile.writeTo(this.filer);
    } catch (IOException e) {
        this.processorUtil.error(typeElement, e.getMessage());
    }
}
 
Example 16
Project: resourceprovider   File: UnnamedPackageException.java   View Source Code Vote up 4 votes
public UnnamedPackageException(TypeElement typeElement) {
  super("The package of " + typeElement.getSimpleName() + " is unnamed");
}
 
Example 17
Project: vulture   File: VultureProcessor.java   View Source Code Vote up 4 votes
private String getTargetClassName(TypeElement originalClass) {
    return "Safe" + originalClass.getSimpleName();
}
 
Example 18
Project: Aurora   File: NoPackageNameException.java   View Source Code Vote up 4 votes
public NoPackageNameException(TypeElement typeElement) {
    super("The package of " + typeElement.getSimpleName() + " has no name");
}
 
Example 19
Project: pluginMVPM   File: NoPackageNameException.java   View Source Code Vote up 4 votes
public NoPackageNameException(TypeElement typeElement) {
    super("The package of " + typeElement.getSimpleName() + " has no name");
}
 
Example 20
Project: drd   File: ManagerProcessor.java   View Source Code Vote up 4 votes
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    System.out.println("Zpracovavam annotace");
    messager.printMessage(Kind.WARNING, "Zpracovavam annotace");
    for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(Table.class)) {
        if (annotatedElement.getKind() != ElementKind.CLASS) {
            error(messager, annotatedElement, "Only classes can be annotated with @%s",
                Table.class.getSimpleName());
            return true; // Exit processing
        }
        TypeElement typeElement = (TypeElement) annotatedElement;
        TableAnnotatedClass tableAnnotatedClass = new TableAnnotatedClass(typeElement);
        messager.printMessage(Kind.NOTE, "Zpracovávám třídu: " + tableAnnotatedClass.getSimpleTypeName());

        final List<ColumnInfo> columnInfos = new ArrayList<>();
        final Field[] fields = annotatedElement.getClass().getDeclaredFields();
        for (Field field : fields) {
            Column columnAnnotation = field.getAnnotation(Column.class);
            if (columnAnnotation == null) {
                continue;
            }

            messager.printMessage(Kind.NOTE, "Přidávám field: " + field.getName());
            columnInfos.add(new ColumnInfo(columnAnnotation.name(), field.getType()));
        }

        System.out.println("Test processor");

        try {
            final String className = typeElement.getSimpleName() + "Manager";
            final JavaFileObject fileObject = processingEnv.getFiler().createSourceFile(
                typeElement.getQualifiedName() + "." + className);

            try(Writer writter = fileObject.openWriter()) {
                writter.append( "package " + typeElement.getQualifiedName() + ";" );
                writter.append( "\\n\\n");
                writter.append( "public class " + className + " {" );
                writter.append( "\\n");
                writter.append( "}");
            }
        } catch( final IOException ex ) {
            processingEnv.getMessager().printMessage(Kind.ERROR, ex.getMessage());
        }

    }
    return true;
}