Java Code Examples for com.squareup.javapoet.ClassName#get()

The following examples show how to use com.squareup.javapoet.ClassName#get() . 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: JPredicateCodeGenerator.java    From jackdaw with Apache License 2.0 6 votes vote down vote up
private TypeName getFieldType(
    final JPredicateType type, final TypeElement typeElement
) {
    final String packageName = getPredicatePackageName(type);
    switch (type) {
        case GUAVA:
        case JAVA:
            return ParameterizedTypeName.get(
                ClassName.get(packageName, CLASS_NAME),
                TypeUtils.getTypeName(typeElement)
            );
        case COMMONS:
            return ClassName.get(packageName, CLASS_NAME);
        default:
            throw new UnsupportedOperationException();
    }
}
 
Example 2
Source File: ModuleDumperClassPoolVisitor.java    From reflection-no-reflection with Apache License 2.0 6 votes vote down vote up
private MethodSpec createConstructor() {
    MethodSpec.Builder constructorSpecBuilder = MethodSpec.constructorBuilder();
    constructorSpecBuilder.addModifiers(Modifier.PUBLIC);

    ClassName setTypeName = ClassName.get("java.util", "Set");
    TypeName setOfStringTypeName = ParameterizedTypeName.get(setTypeName, STRING_TYPE_NAME);
    ClassName hashSetTypeName = ClassName.get("java.util", "HashSet");

    int annotationClassCounter = 0;
    for (Map.Entry<Class<? extends Annotation>, Set<Class<?>>> entry : mapAnnotationTypeToClassContainingAnnotation.entrySet()) {
        constructorSpecBuilder.addStatement("$T s$L = new $T()", setOfStringTypeName, annotationClassCounter, hashSetTypeName);
        for (Class<?> clazz : entry.getValue()) {
            constructorSpecBuilder.addStatement("s$L.add($S)", annotationClassCounter, clazz.getName());
        }
        String annotationTypeName = entry.getKey().getName();
        constructorSpecBuilder.addStatement("mapAnnotationNameToNameOfClassesContainingAnnotation.put($S,s$L)", annotationTypeName, annotationClassCounter);
        constructorSpecBuilder.addCode("\n");
        annotationClassCounter++;
    }
    return constructorSpecBuilder.build();
}
 
Example 3
Source File: BuilderProcessor.java    From customview-samples with Apache License 2.0 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    for (Element element : roundEnv.getElementsAnnotatedWith(Builder.class)) {
        if (element.getKind() != ElementKind.CLASS) {
            onError("Builder annotation can only be applied to class", element);
            return false;
        }

        String packageName = elementUtils.getPackageOf(element).getQualifiedName().toString();
        String elementName = element.getSimpleName().toString();
        ClassName builderClassName = ClassName.get(packageName, String.format("%sBuilder", elementName));

        TypeSpec typeSpec = createTypeSpec(element, builderClassName, elementName);

        JavaFile javaFile = JavaFile.builder(packageName, typeSpec).build();
        try {
            javaFile.writeTo(filer);
        } catch (IOException e) {
            onError("Failed to write java file: " + e.getMessage(), element);
        }
    }
    return true;
}
 
Example 4
Source File: AsyncClientBuilderClass.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
public AsyncClientBuilderClass(IntermediateModel model) {
    String basePackage = model.getMetadata().getFullClientPackageName();
    this.model = model;
    this.clientInterfaceName = ClassName.get(basePackage, model.getMetadata().getAsyncInterface());
    this.clientClassName = ClassName.get(basePackage, model.getMetadata().getAsyncClient());
    this.builderInterfaceName = ClassName.get(basePackage, model.getMetadata().getAsyncBuilderInterface());
    this.builderClassName = ClassName.get(basePackage, model.getMetadata().getAsyncBuilder());
    this.builderBaseClassName = ClassName.get(basePackage, model.getMetadata().getBaseBuilder());
}
 
Example 5
Source File: ModelGenerator.java    From requery with Apache License 2.0 5 votes vote down vote up
@Override
public void generate() throws IOException {
    ClassName typeName = ClassName.get(packageName, "Models");
    TypeSpec.Builder type = TypeSpec.classBuilder(typeName)
            .addModifiers(Modifier.PUBLIC)
            .addMethod(MethodSpec.constructorBuilder()
                    .addModifiers(Modifier.PRIVATE).build());
    CodeGeneration.addGeneratedAnnotation(processingEnvironment, type);

    Map<String, Set<EntityDescriptor>> models = new HashMap<>();
    Comparator<EntityDescriptor> comparator =
            Comparator.comparing(descriptor -> descriptor.typeName().toString());
    entities.forEach(entity ->
            models.computeIfAbsent(entity.modelName(), key -> new TreeSet<>(comparator)).add(entity));

    for (String model : models.keySet()) {
        Set<EntityDescriptor> types = models.get(model);

        FieldSpec.Builder field = FieldSpec.builder(ClassName.get(EntityModel.class),
                model.toUpperCase(), Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL);
        CodeBlock.Builder fieldType = CodeBlock.builder();
        fieldType.add("new $T($S)\n", ClassName.get(EntityModelBuilder.class), model);

        types.forEach(e -> fieldType.add(".addType($T.$L)\n",
                ClassName.bestGuess(e.typeName().toString()), EntityGenerator.TYPE_NAME));

        fieldType.add(".build()");
        field.initializer("$L", fieldType.build());
        type.addField(field.build());
    }

    CodeGeneration.writeType(processingEnvironment, typeName.packageName(), type.build());
}
 
Example 6
Source File: ExtraUtilityClassBuilder.java    From PrettyBundle with Apache License 2.0 5 votes vote down vote up
private MethodSpec createIntentMethodSpec(Elements elementUtils, Types typeUtils, ExtraClassesGrouped extraClassesGrouped) {
    final String activityQualifiedClassName = extraClassesGrouped.getExtraAnnotatedClassName();
    final TypeElement typeElement = elementUtils.getTypeElement(activityQualifiedClassName);
    final String activityName = typeElement.getSimpleName().toString();

    // Declare method name.
    final MethodSpec.Builder methodSpecBuilder = MethodSpec.methodBuilder("create" + activityName + "Intent")
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
            .returns(Androids.intentClass());

    // Build parameters.
    // Add Context object.

    methodSpecBuilder.addParameter(Androids.contextClass(), "context");
    buildParameters(methodSpecBuilder, extraClassesGrouped);

    ClassName bundleClass = ClassName.get("android.os", "Bundle");

    // Declare bundle object.
    methodSpecBuilder.addStatement("$T bundle = new $T()", bundleClass, bundleClass);
    // Put extras base on key, value to bundle.
    bindExtras(methodSpecBuilder, extraClassesGrouped, "bundle");

    // Build and return Intent.
    return methodSpecBuilder.addStatement("$T intent = new $T(context, $L)", Androids.intentClass(), Androids.intentClass(), extraClassesGrouped.getExtraAnnotatedClassName() + ".class")
            .addStatement("intent.putExtras(bundle)")
            .addStatement("return intent")
            .build();
}
 
Example 7
Source File: PaperParcelAutoValueExtension.java    From paperparcel with Apache License 2.0 5 votes vote down vote up
private MethodSpec writeToParcel(ClassName className) {
  ClassName parcelableImplClassName =
      ClassName.get(className.packageName(), "PaperParcel" + className.simpleName());
  return MethodSpec.methodBuilder("writeToParcel")
      .addAnnotation(Override.class)
      .addModifiers(PUBLIC)
      .addParameter(PARCEL, "dest")
      .addParameter(int.class, "flags")
      .addStatement("$T.writeToParcel(this, dest, flags)", parcelableImplClassName)
      .build();
}
 
Example 8
Source File: AndroidResourceSanner.java    From convalida with Apache License 2.0 5 votes vote down vote up
private static void parseCompiledR(String respectivePackageName, TypeElement rClass) {
    for (Element element : rClass.getEnclosedElements()) {
        String innerClassName = element.getSimpleName().toString();
        if (innerClassName.equals("string")) {
            for (Element enclosedElement : element.getEnclosedElements()) {
                if (enclosedElement instanceof VariableElement) {
                    VariableElement variableElement = (VariableElement) enclosedElement;
                    Object value = variableElement.getConstantValue();

                    if (value instanceof Integer) {
                        int id = (Integer) value;
                        ClassName rClassName = ClassName.get(
                                scanner.elementUtils.getPackageOf(variableElement).toString(),
                                "R",
                                innerClassName
                        );

                        String resourceName = variableElement.getSimpleName().toString();

                        QualifiedId qualifiedId = new QualifiedId(respectivePackageName, id);

                        scanner.symbols.put(qualifiedId, new Id(id, rClassName, resourceName));
                    }
                }
            }
        }
    }
}
 
Example 9
Source File: ViewElement.java    From sqlitemagic with Apache License 2.0 5 votes vote down vote up
private void determineImplementationClassName() {
  final String abstractClassName;
  if (isInterface) {
    abstractClassName = String.format("%s_%sImpl",
        EntityEnvironment.getGeneratedDaoClassNameString(getViewElement()),
        getViewElementName());
  } else {
    abstractClassName = getViewElementName();
  }
  this.abstractClassNameString = abstractClassName;
  this.implementationClassName = ClassName.get(getPackageName(), environment.getValueImplementationClassNameString(abstractClassName));
}
 
Example 10
Source File: AsyncClientInterface.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Generate a simple method for operations with a streaming output member that takes a {@link Path} where data
 * will be downloaded to.
 */
private MethodSpec streamingOutputFileSimpleMethod(OperationModel opModel) {
    ClassName requestType = ClassName.get(modelPackage, opModel.getInput().getVariableType());
    return interfaceMethodSignature(opModel)
            .returns(completableFutureType(getPojoResponseType(opModel)))
            .addJavadoc(opModel.getDocs(model, ClientType.ASYNC, SimpleMethodOverload.FILE))
            .addParameter(requestType, opModel.getInput().getVariableName())
            .addParameter(ClassName.get(Path.class), "destinationPath")
            .addStatement("return $L($L, $T.toFile(destinationPath))", opModel.getMethodName(),
                          opModel.getInput().getVariableName(),
                          ClassName.get(AsyncResponseTransformer.class))
            .build();
}
 
Example 11
Source File: ColumnEntry.java    From RapidORM with Apache License 2.0 5 votes vote down vote up
public ColumnEntry(Element fieldColumnElement, Element classElement) {
    this.fieldColumnElement = fieldColumnElement;
    fieldSimpleName = fieldColumnElement.getSimpleName().toString();
    column = fieldColumnElement.getAnnotation(Column.class);
    columnName = getColumnName(fieldSimpleName, column);
    fieldColumnTypeName = ClassName.get(fieldColumnElement.asType());
    dbType = parseDbType(fieldColumnTypeName);
    dataType = parseDataType(fieldColumnTypeName);
    this.classElement = classElement;
}
 
Example 12
Source File: ControllerProcessor.java    From AndServer with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
    super.init(processingEnv);
    mFiler = processingEnv.getFiler();
    mElements = processingEnv.getElementUtils();
    mLog = new Logger(processingEnv.getMessager());

    mContext = TypeName.get(mElements.getTypeElement(Constants.CONTEXT_TYPE).asType());
    mStringUtils = TypeName.get(mElements.getTypeElement(Constants.STRING_UTIL_TYPE).asType());
    mCollectionUtils = TypeName.get(mElements.getTypeElement(Constants.COLLECTION_UTIL_TYPE).asType());
    mTypeWrapper = ClassName.get(mElements.getTypeElement(Constants.TYPE_WRAPPER_TYPE));
    mMediaType = TypeName.get(mElements.getTypeElement(Constants.MEDIA_TYPE).asType());
    mOnRegisterType = TypeName.get(mElements.getTypeElement(Constants.ON_REGISTER_TYPE).asType());
    mRegisterType = TypeName.get(mElements.getTypeElement(Constants.REGISTER_TYPE).asType());

    mBodyMissing = TypeName.get(mElements.getTypeElement(Constants.BODY_MISSING).asType());
    mCookieMissing = TypeName.get(mElements.getTypeElement(Constants.COOKIE_MISSING).asType());
    mParamMissing = TypeName.get(mElements.getTypeElement(Constants.PARAM_MISSING).asType());
    mHeaderMissing = TypeName.get(mElements.getTypeElement(Constants.HEADER_MISSING).asType());
    mPathMissing = TypeName.get(mElements.getTypeElement(Constants.PATH_MISSING).asType());
    mParamError = TypeName.get(mElements.getTypeElement(Constants.PARAM_ERROR).asType());

    mConverter = TypeName.get(mElements.getTypeElement(Constants.CONVERTER_TYPE).asType());
    mAdapter = TypeName.get(mElements.getTypeElement(Constants.ADAPTER_TYPE).asType());
    mMappingAdapter = TypeName.get(mElements.getTypeElement(Constants.MAPPING_ADAPTER_TYPE).asType());
    mHandler = TypeName.get(mElements.getTypeElement(Constants.HANDLER_TYPE).asType());
    mMappingHandler = TypeName.get(mElements.getTypeElement(Constants.MAPPING_HANDLER_TYPE).asType());
    mView = TypeName.get(mElements.getTypeElement(Constants.VIEW_TYPE).asType());
    mViewObject = TypeName.get(mElements.getTypeElement(Constants.VIEW_TYPE_OBJECT).asType());

    mRequest = TypeName.get(mElements.getTypeElement(Constants.REQUEST_TYPE).asType());
    mMultipartRequest = TypeName.get(mElements.getTypeElement(Constants.MULTIPART_REQUEST_TYPE).asType());
    mResponse = TypeName.get(mElements.getTypeElement(Constants.RESPONSE_TYPE).asType());
    mHttpMethod = TypeName.get(mElements.getTypeElement(Constants.HTTP_METHOD_TYPE).asType());
    mSession = TypeName.get(mElements.getTypeElement(Constants.SESSION_TYPE).asType());
    mRequestBody = TypeName.get(mElements.getTypeElement(Constants.REQUEST_BODY_TYPE).asType());
    mMultipartFile = TypeName.get(mElements.getTypeElement(Constants.MULTIPART_FILE_TYPE).asType());
    mMultipartFileArray = ArrayTypeName.of(mMultipartFile);
    mMultipartFileList = ParameterizedTypeName.get(ClassName.get(List.class), mMultipartFile);

    mAddition = TypeName.get(mElements.getTypeElement(Constants.ADDITION_TYPE).asType());
    mMapping = TypeName.get(mElements.getTypeElement(Constants.MAPPING_TYPE).asType());
    mMimeTypeMapping = TypeName.get(mElements.getTypeElement(Constants.MIME_MAPPING_TYPE).asType());
    mMethodMapping = TypeName.get(mElements.getTypeElement(Constants.METHOD_MAPPING_TYPE).asType());
    mPairMapping = TypeName.get(mElements.getTypeElement(Constants.PAIR_MAPPING_TYPE).asType());
    mPathMapping = TypeName.get(mElements.getTypeElement(Constants.PATH_MAPPING_TYPE).asType());
    mMappingList = ParameterizedTypeName.get(ClassName.get(Map.class), mMapping, mHandler);
}
 
Example 13
Source File: TableProcessor.java    From wellsql with MIT License 4 votes vote down vote up
private String createTable(Element tableElement, TableAnnotatedClass table) {

        String genClassName = table.getTableName() + "Table";
        TypeSpec.Builder tableClassBuilder = TypeSpec.classBuilder(genClassName)
                .addModifiers(Modifier.FINAL, Modifier.PUBLIC)
                .addSuperinterface(TableClass.class);

        MethodSpec createStatement = CodeGenUtils.interfaceMethod("createStatement")
                .returns(String.class)
                .addStatement("return $S", table.toTableDeclaration())
                .build();
        MethodSpec tableName = CodeGenUtils.interfaceMethod("getTableName")
                .returns(String.class)
                .addStatement("return $S", table.getTableName())
                .build();
        TypeName model = ClassName.get(tableElement.asType());
        MethodSpec modelClass = CodeGenUtils.interfaceMethod("getModelClass")
                .returns(CodeGenUtils.wildcard(Class.class))
                .addStatement("return $T.class", model)
                .build();
        MethodSpec isAutoincrement = CodeGenUtils.interfaceMethod("shouldAutoincrementId")
                .returns(boolean.class)
                .addStatement("return " + table.isAutoincrement())
                .build();

        tableClassBuilder.addMethod(createStatement)
                .addMethod(tableName)
                .addMethod(modelClass)
                .addMethod(isAutoincrement);

        for (ColumnAnnotatedField column : table.columns()) {
            tableClassBuilder.addField(columnToStaticConstant(column));
        }

        TypeSpec tableClass = tableClassBuilder.build();
        JavaFile javaFile = JavaFile.builder(CodeGenUtils.PACKAGE, tableClass)
                .build();

        try {
            javaFile.writeTo(filer);
        } catch (IOException e) {
            error(tableElement, "Failed to create file: " + e.getMessage());
        }

        return CodeGenUtils.PACKAGE + "." + genClassName;
    }
 
Example 14
Source File: PoetExtensions.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
/**
 * @return ResponseMetadata className. eg: "S3ResponseMetadata"
 */
public ClassName getResponseMetadataClass() {
    return ClassName.get(model.getMetadata().getFullModelPackageName(),
                         model.getSdkResponseBaseClassName() + "Metadata");
}
 
Example 15
Source File: ProcessUtils.java    From RxAndroidOrm with Apache License 2.0 4 votes vote down vote up
public static TypeName getQueryBuilder(Element element) {
    return ClassName.get(getObjectPackage(element), getObjectName(element) + Constants.QUERY_BUILDER_SUFFIX);
}
 
Example 16
Source File: SQLiteOpenHelperClass.java    From HighLite with Apache License 2.0 4 votes vote down vote up
private ClassName getHelperClassName() {
    return ClassName.get(mPackageName,
            (String.valueOf(mDatabaseName.charAt(0)).toUpperCase()
                    + mDatabaseName.substring(1) + "_OpenHelper").replaceAll("\\.", "_"));
}
 
Example 17
Source File: EntityNameResolver.java    From requery with Apache License 2.0 4 votes vote down vote up
ClassName embeddedTypeNameOf(EntityDescriptor embedded, EntityDescriptor parent) {
    String className = parent.typeName().className() + "_" + embedded.typeName().className();
    return ClassName.get(parent.typeName().packageName(), className);
}
 
Example 18
Source File: FileUtils.java    From Witch-Android with Apache License 2.0 4 votes vote down vote up
public static ClassName getMagicTargetViewBinderClassName(Element target) {
    String className = MAGIC_VIEW_BINDER_PREFIX + target.getSimpleName().toString();
    String packageName = FileUtils.getElementPackage(target);
    return ClassName.get(packageName,className);
}
 
Example 19
Source File: SpotCompiler.java    From spot with Apache License 2.0 4 votes vote down vote up
private void handlePrefLong(Element element1, MethodSpec.Builder getEntitySpecBuilder,
                           MethodSpec.Builder putEntitySpecBuilder) {
    ClassName utilClass = ClassName.get(PreferencesUtil.class);
    PrefField pref = element1.getAnnotation(PrefField.class);

    TypeName converterClass = getConverterClass(pref);

    getEntitySpecBuilder.beginControlFlow("if ($T.contains(context, getName(), $S))", utilClass, pref.name());

    if (pref.useSetter()) {
        String setterName = getSetterName(element1.getSimpleName().toString());
        getEntitySpecBuilder.addStatement(
                "entity.$L ( new $T().convertFromSupportedType( $T.getLong(context, getName(), $S, $L) ) )",
                setterName,
                converterClass,
                utilClass,
                pref.name(),
                0L);
    } else {
        getEntitySpecBuilder.addStatement(
                "entity.$N = new $T().convertFromSupportedType( $T.getLong(context, getName(), $S, $L) )",
                element1.getSimpleName(),
                converterClass,
                utilClass,
                pref.name(),
                0L);
    }

    getEntitySpecBuilder.endControlFlow();

    if (pref.useGetter()) {
        String getterName = getGetterName(element1.getSimpleName().toString());
        putEntitySpecBuilder.addStatement(
                "$T.putLong(context, getName(), $S, new $T().convertToSupportedType(entity.$N()))",
                utilClass,
                pref.name(),
                converterClass,
                getterName);
    } else {
        putEntitySpecBuilder.addStatement(
                "$T.putLong(context, getName(), $S, new $T().convertToSupportedType(entity.$N))",
                utilClass,
                pref.name(),
                converterClass,
                element1.getSimpleName());
    }
}
 
Example 20
Source File: FactoryWriter.java    From auto with Apache License 2.0 3 votes vote down vote up
/**
 * Returns an appropriate {@code TypeName} for the given type. If the type is an
 * {@code ErrorType}, and if it is a simple-name reference to one of the {@code *Factory}
 * classes that we are going to generate, then we return its fully-qualified name. In every other
 * case we just return {@code TypeName.get(type)}. Specifically, if it is an {@code ErrorType}
 * referencing some other type, or referencing one of the classes we are going to generate but
 * using its fully-qualified name, then we leave it as-is. JavaPoet treats {@code TypeName.get(t)}
 * the same for {@code ErrorType} as for {@code DeclaredType}, which means that if this is a name
 * that will eventually be generated then the code we write that references the type will in fact
 * compile.
 *
 * <p>A simpler alternative would be to defer processing to a later round if we find an
 * {@code @AutoFactory} class that references undefined types, under the assumption that something
 * else will generate those types in the meanwhile. However, this would fail if for example
 * {@code @AutoFactory class Foo} has a constructor parameter of type {@code BarFactory} and
 * {@code @AutoFactory class Bar} has a constructor parameter of type {@code FooFactory}. We did
 * in fact find instances of this in Google's source base.
 */
private TypeName resolveTypeName(TypeMirror type) {
  if (type.getKind() != TypeKind.ERROR) {
    return TypeName.get(type);
  }
  ImmutableSet<PackageAndClass> factoryNames = factoriesBeingCreated.get(type.toString());
  if (factoryNames.size() == 1) {
    PackageAndClass packageAndClass = Iterables.getOnlyElement(factoryNames);
    return ClassName.get(packageAndClass.packageName(), packageAndClass.className());
  }
  return TypeName.get(type);
}