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

The following examples show how to use com.squareup.javapoet.ClassName#bestGuess() . 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: NavigationFactoryGenerator.java    From Alligator with MIT License 6 votes vote down vote up
public JavaFile generate(List<RegistrationAnnotatedClass> annotatedClasses) throws ProcessingException {
	MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder()
			.addModifiers(Modifier.PUBLIC);

	for (RegistrationAnnotatedClass annotatedClass : annotatedClasses) {
		ClassName annotatedClassName = ClassName.get(annotatedClass.getClassElement());
		ClassName screenClassName = ClassName.bestGuess(annotatedClass.getScreenClassName());

		if (annotatedClass.getScreenResultClassName() == null) {
			String registrationMethod = getRegistrationMethod(annotatedClass.getScreenType());
			constructorBuilder.addStatement(registrationMethod, screenClassName, annotatedClassName);
		} else {
			String registrationForResultMethod = getRegistrationForResultMethod(annotatedClass.getScreenType());
			ClassName screenResultClassName = ClassName.bestGuess(annotatedClass.getScreenResultClassName());
			constructorBuilder.addStatement(registrationForResultMethod, screenClassName, annotatedClassName, screenResultClassName);
		}
	}

	TypeSpec navigationFactory = TypeSpec.classBuilder(CLASS_NAME)
			.addModifiers(Modifier.PUBLIC)
			.superclass(ClassName.get(PACKAGE, SUPERCLASS_NAME))
			.addMethod(constructorBuilder.build())
			.build();

	return JavaFile.builder(PACKAGE, navigationFactory).build();
}
 
Example 2
Source File: RouterComponentCodeBuilder.java    From grouter-android with Apache License 2.0 5 votes vote down vote up
public static JavaFile getJavaFile(String centerName, List<ComponentModel> componentModels) {
    TypeSpec.Builder componentHelper = TypeSpec.classBuilder(centerName)
            .addModifiers(Modifier.PUBLIC);
    ClassName ComponentUtils = ClassName.bestGuess("com.grouter.ComponentUtils");

    for (ComponentModel component : componentModels) {
        ClassName protocol = ClassName.bestGuess(component.protocol);
        ClassName implement = ClassName.bestGuess(component.implement);


        for (ComponentModel.ConstructorBean constructor : component.constructors) {
            MethodSpec.Builder methodSpec = MethodSpec.methodBuilder(implement.simpleName())
                    .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                    .returns(protocol);
            if (constructor.parameterTypes.size() > 0) {
                methodSpec.addStatement("Class[] classes = new Class[$L]", constructor.parameterTypes.size());
                methodSpec.addStatement("Object[] objects = new Object[$L]", constructor.parameterTypes.size());
                for (int i = 0; i < constructor.parameterTypes.size(); i++) {
                    String clazz = constructor.parameterTypes.get(i);
                    String name = constructor.parameterNames.get(i);
                    TypeName typeName = TypeUtils.getTypeNameFull(clazz);
                    methodSpec.addParameter(typeName, name);
                    if (typeName instanceof ParameterizedTypeName) {
                        methodSpec.addStatement("classes[$L] = $T.class", i, ((ParameterizedTypeName) typeName).rawType);
                    } else {
                        methodSpec.addStatement("classes[$L] = $T.class", i, typeName);
                    }
                    methodSpec.addStatement("objects[$L] = $N", i, name);
                }
                methodSpec.addStatement("return $T.getInstance($T.class,$S,classes,objects)", ComponentUtils, protocol, TypeUtils.reflectionName(implement));
            } else {
                methodSpec.addStatement("return $T.getInstance($T.class,$S)", ComponentUtils, protocol, TypeUtils.reflectionName(implement));
            }
            componentHelper.addMethod(methodSpec.build());
        }
    }
    AnnotationSpec annotationSpec = AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "\"unused\"").build();
    componentHelper.addAnnotation(annotationSpec);
    return JavaFile.builder("com.grouter", componentHelper.build()).build();
}
 
Example 3
Source File: SpotCompiler.java    From spot with Apache License 2.0 5 votes vote down vote up
private TypeName getConverterClass(PrefField prefField) {
    TypeMirror typeMirror = null;
    try {
        prefField.converter();
    } catch (MirroredTypeException e) {
        typeMirror = e.getTypeMirror();
    }
    return ClassName.bestGuess(typeMirror.toString());
}
 
Example 4
Source File: EasyType.java    From RapidORM with Apache License 2.0 5 votes vote down vote up
/**
 * @param type
 * @return
 */
public static TypeName bestGuessDeep(String type) {
    switch (type) {
        case "void":
            return TypeName.VOID;
        case "boolean":
            return TypeName.BOOLEAN;
        case "byte":
            return TypeName.BYTE;
        case "char":
            return TypeName.CHAR;
        case "double":
            return TypeName.DOUBLE;
        case "float":
            return TypeName.FLOAT;
        case "int":
            return TypeName.INT;
        case "long":
            return TypeName.LONG;
        case "short":
            return TypeName.SHORT;
        default:
            int left = type.indexOf('<');
            int right = type.indexOf('>');
            if (-1 != left && -1 != right) {
                ClassName typeClassName = ClassName.bestGuess(type.substring(0, left));
                List<TypeName> typeArguments = new ArrayList<>();
                do {
                    typeArguments.add(WildcardTypeName.subtypeOf(bestGuess(type.substring(left + 1, right))));
                    left = type.indexOf('<', left + 1);
                    right = type.indexOf('>', right - 1);
                } while (left != -1);
                return ParameterizedTypeName.get(typeClassName,
                        typeArguments.toArray(new TypeName[typeArguments.size()]));
            }
            return ClassName.bestGuess(type);
    }
}
 
Example 5
Source File: SimpleProcessorTests.java    From spring-init with Apache License 2.0 5 votes vote down vote up
private static TypeSpec.Builder importAnnotation(TypeSpec.Builder type, String... fullyQualifiedImports) {
	ClassName[] array = new ClassName[fullyQualifiedImports.length];
	for (int i = 0; i < fullyQualifiedImports.length; i++) {
		array[i] = ClassName.bestGuess(fullyQualifiedImports[i]);
	}
	AnnotationSpec.Builder builder = AnnotationSpec.builder(IMPORT);
	builder.addMember("value", array.length > 1 ? ("{" + typeParams(array.length) + "}") : "$T.class",
			(Object[]) array);
	return type.addAnnotation(builder.build());
}
 
Example 6
Source File: SpecModelImpl.java    From litho with Apache License 2.0 5 votes vote down vote up
private static ClassName getComponentTypeName(
    String componentClassName, String qualifiedSpecClassName) {
  final String qualifiedComponentClassName;
  if (componentClassName == null || componentClassName.isEmpty()) {
    qualifiedComponentClassName =
        qualifiedSpecClassName.substring(
            0, qualifiedSpecClassName.length() - SPEC_SUFFIX.length());
  } else {
    qualifiedComponentClassName =
        qualifiedSpecClassName.substring(0, qualifiedSpecClassName.lastIndexOf('.') + 1)
            + componentClassName;
  }

  return ClassName.bestGuess(qualifiedComponentClassName);
}
 
Example 7
Source File: EasyType.java    From RapidORM with Apache License 2.0 5 votes vote down vote up
public static TypeName bestGuess(String type) {
    switch (type) {
        case "void":
            return TypeName.VOID;
        case "boolean":
            return TypeName.BOOLEAN;
        case "byte":
            return TypeName.BYTE;
        case "char":
            return TypeName.CHAR;
        case "double":
            return TypeName.DOUBLE;
        case "float":
            return TypeName.FLOAT;
        case "int":
            return TypeName.INT;
        case "long":
            return TypeName.LONG;
        case "short":
            return TypeName.SHORT;
        default:
            int left = type.indexOf('<');
            if (left != -1) {
                ClassName typeClassName = ClassName.bestGuess(type.substring(0, left));
                List<TypeName> typeArguments = new ArrayList<>();
                do {
                    typeArguments.add(WildcardTypeName.subtypeOf(Object.class));
                    left = type.indexOf('<', left + 1);
                } while (left != -1);
                return ParameterizedTypeName.get(typeClassName,
                        typeArguments.toArray(new TypeName[typeArguments.size()]));
            }
            return ClassName.bestGuess(type);
    }
}
 
Example 8
Source File: SerializerInstanceBuilderTest.java    From domino-jackson with Apache License 2.0 5 votes vote down vote up
@Test
public void testNestedBeanTypeField() throws Exception {

    ClassName serializer = ClassName.bestGuess("org.dominokit.jacksonapt.processor.TestBeanBeanJsonSerializerImpl");
    TypeRegistry.registerSerializer("org.dominokit.jacksonapt.processor.TestBean", serializer);
    addFieldTest("testBean", result -> assertEquals(buildTestString("new $T()", serializer), result));

    runTests();
}
 
Example 9
Source File: TypeUtils.java    From data-mediator with Apache License 2.0 5 votes vote down vote up
public static TypeName getTypeName(String type){
    switch (type){
        case NAME_int:
            return TypeName.INT;

        case NAME_long:
            return TypeName.LONG;

        case NAME_short:
            return TypeName.SHORT;

        case NAME_byte:
            return TypeName.BYTE;

        case NAME_boolean:
            return TypeName.BOOLEAN;

        case NAME_float:
            return TypeName.FLOAT;

        case NAME_double:
            return TypeName.DOUBLE;

        case NAME_char:
            return TypeName.CHAR;

        case NAME_void:
            return TypeName.VOID;
    }
    return ClassName.bestGuess(type);
}
 
Example 10
Source File: EBHandlerManagerGenerator.java    From EasyBridge with MIT License 5 votes vote down vote up
public static JavaFile brewJava(List<BridgeHandlerModel> handlerModelList) {

        TypeSpec.Builder typeBuilder = classBuilder(CLASS_NAME).addModifiers(PUBLIC, FINAL);

        ClassName bridgeWebView = ClassName.bestGuess(BRIDGE_WEB_VIEW_CLASS);


        MethodSpec.Builder registerMethodBuilder = methodBuilder(REGISTER_METHOD_NAME)
                .addModifiers(PUBLIC, STATIC)
                .addParameter(bridgeWebView, WEB_VIEW_PARAMETER)
                .returns(TypeName.VOID);

        registerMethodBuilder.addCode("\n");
        if (handlerModelList != null && !handlerModelList.isEmpty()) {
            for (BridgeHandlerModel model : handlerModelList) {
                if (model == null) {
                    continue;
                }
                ClassName handlerClass = ClassName.bestGuess(model.className);
                String tempName = model.handlerName + "Handler";
                registerMethodBuilder.addStatement("$T $L = new $T($S,$L)", handlerClass, tempName, handlerClass, model.handlerName, WEB_VIEW_PARAMETER);
                registerMethodBuilder.addStatement("$L.registerHandler($L)", WEB_VIEW_PARAMETER, tempName);
                registerMethodBuilder.addCode("\n");
            }
        }

        typeBuilder.addJavadoc("using {@link #register(BridgeWebView)}to register the instance of BridgeHandler when init the webview of the page\n");

        typeBuilder.addMethod(registerMethodBuilder.build());

        return JavaFile.builder(PACKAGE_NAME, typeBuilder.build())
                .addFileComment("Generated code from EBHandlerManagerGenerator. Do not modify!")
                .build();
    }
 
Example 11
Source File: Generator.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
private void addClientInterfaces(final State state, final TypeSpec.Builder serviceClassBuilder) {
    state.clientClass = ClassName.bestGuess(sanitizeIdentifier(state.serviceProto.getName(), false) + "Client");
    state.filterableClientClass = state.clientClass.peerClass("Filterable" + state.clientClass.simpleName());
    state.blockingClientClass = state.clientClass.peerClass(Blocking + state.clientClass.simpleName());

    final TypeSpec.Builder clientSpecBuilder = interfaceBuilder(state.clientClass)
            .addModifiers(PUBLIC)
            .addSuperinterface(state.filterableClientClass)
            .addSuperinterface(ParameterizedTypeName.get(GrpcClient, state.blockingClientClass));

    final TypeSpec.Builder filterableClientSpecBuilder = interfaceBuilder(state.filterableClientClass)
            .addModifiers(PUBLIC)
            .addSuperinterface(FilterableGrpcClient);

    final TypeSpec.Builder blockingClientSpecBuilder = interfaceBuilder(state.blockingClientClass)
            .addModifiers(PUBLIC)
            .addSuperinterface(ParameterizedTypeName.get(BlockingGrpcClient, state.clientClass));

    state.clientMetaDatas.forEach(clientMetaData -> {
        clientSpecBuilder
                .addMethod(newRpcMethodSpec(clientMetaData.methodProto, EnumSet.of(INTERFACE, CLIENT),
                        (__, b) -> b.addModifiers(ABSTRACT)));

        filterableClientSpecBuilder
                .addMethod(newRpcMethodSpec(clientMetaData.methodProto, EnumSet.of(INTERFACE, CLIENT),
                        (__, b) -> b.addModifiers(ABSTRACT)
                                .addParameter(clientMetaData.className, metadata)));

        blockingClientSpecBuilder
                .addMethod(newRpcMethodSpec(clientMetaData.methodProto, EnumSet.of(BLOCKING, INTERFACE, CLIENT),
                        (__, b) -> b.addModifiers(ABSTRACT)))
                .addMethod(newRpcMethodSpec(clientMetaData.methodProto, EnumSet.of(BLOCKING, INTERFACE, CLIENT),
                        (__, b) -> b.addModifiers(ABSTRACT)
                                .addParameter(clientMetaData.className, metadata)));
    });

    serviceClassBuilder.addType(clientSpecBuilder.build())
            .addType(filterableClientSpecBuilder.build())
            .addType(blockingClientSpecBuilder.build());
}
 
Example 12
Source File: Generator.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
private void addServiceInterfaces(final State state, final TypeSpec.Builder serviceClassBuilder) {
    TypeSpec interfaceSpec = newServiceInterfaceSpec(state, false);
    state.serviceClass = ClassName.bestGuess(interfaceSpec.name);
    serviceClassBuilder.addType(interfaceSpec);

    interfaceSpec = newServiceInterfaceSpec(state, true);
    state.blockingServiceClass = ClassName.bestGuess(interfaceSpec.name);
    serviceClassBuilder.addType(interfaceSpec);
}
 
Example 13
Source File: BinderFactory.java    From IntentLife with Apache License 2.0 5 votes vote down vote up
/**
 * Add proxy control condition.
 */
private static void addProxyControl(MethodSpec.Builder proxyBindMethodBuilder, String packageName,
                                    String targetClassName, String binderClassName) {
    final TypeName targetTypeName = ClassName.bestGuess(targetClassName);
    final TypeName binderTypeName = ClassName.get(packageName, binderClassName);
    proxyBindMethodBuilder.beginControlFlow(CONDITION_INSTANCE_OF_TARGET_CLASS, targetTypeName)
            .addStatement(STATEMENT_CREATE_BINDER_OBJECT, binderTypeName, binderTypeName)
            .addStatement(STATEMENT_INVOKE_BIND_METHOD, targetTypeName)
            .endControlFlow();
}
 
Example 14
Source File: OpenApiClientGenerator.java    From spring-openapi with MIT License 5 votes vote down vote up
private FieldSpec.Builder createSimpleFieldSpec(String packageName, String className, String fieldName, TypeSpec.Builder typeSpecBuilder) {
	ClassName simpleFieldClassName = packageName == null ? ClassName.bestGuess(className) : ClassName.get(packageName, className);
	if (typeSpecBuilder != null) {
		enrichWithGetSet(typeSpecBuilder, simpleFieldClassName, fieldName);
	}
	return FieldSpec.builder(simpleFieldClassName, fieldName, Modifier.PRIVATE);
}
 
Example 15
Source File: PrestoWrapperGenerator.java    From transport with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private void generateWrapper(String implementationClass, File sourcesOutputDir, List<String> services) {
  ClassName implementationClassName = ClassName.bestGuess(implementationClass);
  ClassName wrapperClassName =
      ClassName.get(implementationClassName.packageName() + "." + PRESTO_PACKAGE_SUFFIX,
          implementationClassName.simpleName());

  /*
    Generates constructor ->

    public ${wrapperClassName}() {
      super(new ${implementationClassName}());
    }
   */
  MethodSpec constructor = MethodSpec.constructorBuilder()
      .addModifiers(Modifier.PUBLIC)
      .addStatement("super(new $T())", implementationClassName)
      .build();

  /*
    Generates ->

    @Override
    protected StdUDF getStdUDF() {
      return new ${implementationClassName}();
    }
   */
  MethodSpec getStdUDFMethod = MethodSpec.methodBuilder(GET_STD_UDF_METHOD)
      .addAnnotation(Override.class)
      .returns(StdUDF.class)
      .addModifiers(Modifier.PROTECTED)
      .addStatement("return new $T()", implementationClassName)
      .build();

  /*
    Generates ->

    public class ${wrapperClassName} extends StdUdfWrapper {

      .
      .
      .

    }
   */
  TypeSpec wrapperClass = TypeSpec.classBuilder(wrapperClassName)
      .addModifiers(Modifier.PUBLIC)
      .superclass(PRESTO_STD_UDF_WRAPPER_CLASS_NAME)
      .addMethod(constructor)
      .addMethod(getStdUDFMethod)
      .build();

  services.add(wrapperClassName.toString());
  JavaFile javaFile = JavaFile.builder(wrapperClassName.packageName(), wrapperClass)
      .skipJavaLangImports(true)
      .build();

  try {
    javaFile.writeTo(sourcesOutputDir);
  } catch (Exception e) {
    throw new RuntimeException("Error writing wrapper to file: ", e);
  }
}
 
Example 16
Source File: DelegateClassGenerator.java    From EasyMVP with Apache License 2.0 4 votes vote down vote up
public void setPresenterTypeInView(String presenterTypeInView) {
    this.presenterTypeInView = ClassName.bestGuess(presenterTypeInView);
}
 
Example 17
Source File: PsiTypeUtils.java    From litho with Apache License 2.0 4 votes vote down vote up
/** @return Returns a {@link ClassName} for the given class name string. */
static ClassName guessClassName(String typeName) {
  return ClassName.bestGuess(typeName);
}
 
Example 18
Source File: EntityNameResolver.java    From requery with Apache License 2.0 4 votes vote down vote up
ClassName typeNameOf(EntityDescriptor type) {
    return ClassName.bestGuess(type.typeName().toString());
}
 
Example 19
Source File: ProcessUtils.java    From RxAndroidOrm with Apache License 2.0 4 votes vote down vote up
public static TypeName getFieldQueryBuilderClass(VariableElement element) {
    return ClassName.bestGuess(getFieldClass(element).toString() + Constants.QUERY_BUILDER_SUFFIX);
}
 
Example 20
Source File: ComponentBodyGenerator.java    From litho with Apache License 2.0 4 votes vote down vote up
public static TypeSpecDataHolder generate(
    SpecModel specModel, @Nullable MethodParamModel optionalField, EnumSet<RunMode> runMode) {
  final TypeSpecDataHolder.Builder builder = TypeSpecDataHolder.newBuilder();

  final boolean hasState = !specModel.getStateValues().isEmpty();
  if (hasState) {
    final ClassName stateContainerClass =
        ClassName.bestGuess(getStateContainerClassName(specModel));
    builder.addField(
        FieldSpec.builder(stateContainerClass, STATE_CONTAINER_FIELD_NAME, Modifier.PRIVATE)
            .addAnnotation(
                AnnotationSpec.builder(Comparable.class)
                    .addMember("type", "$L", Comparable.STATE_CONTAINER)
                    .build())
            .build());
    builder.addMethod(generateStateContainerGetter(specModel.getStateContainerClass()));
  }

  final boolean needsRenderDataInfra = !specModel.getRenderDataDiffs().isEmpty();
  if (needsRenderDataInfra) {
    final ClassName previousRenderDataClass =
        ClassName.bestGuess(RenderDataGenerator.getRenderDataImplClassName(specModel));
    builder.addField(previousRenderDataClass, PREVIOUS_RENDER_DATA_FIELD_NAME, Modifier.PRIVATE);
  }

  builder
      .addTypeSpecDataHolder(generateInjectedFields(specModel))
      .addTypeSpecDataHolder(generateProps(specModel, runMode))
      .addTypeSpecDataHolder(generateTreeProps(specModel, runMode))
      .addTypeSpecDataHolder(generateInterStageInputs(specModel))
      .addTypeSpecDataHolder(generateOptionalField(optionalField))
      .addTypeSpecDataHolder(generateEventHandlers(specModel))
      .addTypeSpecDataHolder(generateEventTriggers(specModel));

  if (specModel.shouldGenerateIsEquivalentTo()) {
    builder.addMethod(generateIsEquivalentMethod(specModel, runMode));
  }

  builder.addTypeSpecDataHolder(generateCopyInterStageImpl(specModel));
  builder.addTypeSpecDataHolder(generateMakeShallowCopy(specModel, hasState));
  builder.addTypeSpecDataHolder(generateGetDynamicProps(specModel));
  builder.addTypeSpecDataHolder(generateBindDynamicProp(specModel));

  if (hasState) {
    builder.addType(StateContainerGenerator.generate(specModel, runMode));
  }
  if (needsRenderDataInfra) {
    builder.addType(generatePreviousRenderDataContainerImpl(specModel));
  }

  return builder.build();
}