Java 类com.squareup.javapoet.CodeBlock 实例源码

项目:jso-builder    文件:SerializerGenerator.java   
private MethodSpec createIsJsObject() {
    CodeBlock.Builder builder = CodeBlock.builder();
    builder.addStatement("$1T jsType = type.getAnnotation($1T.class)", ClassNames.JSINTEROP_JSTYPE);
    Stream.of(
            "jsType == null",
            "!jsType.isNative()",
            "!JsPackage.GLOBAL.equals(jsType.namespace())",
            "!\"Object\".equals(jsType.name())")
        .forEachOrdered(statement -> builder
                .beginControlFlow("if (" + statement + ")")
                    .addStatement("return false")
                .endControlFlow());
    builder.addStatement("return true");

    return MethodSpec.methodBuilder("isJsObject")
            .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
            .addAnnotation(ClassNames.GWT_INCOMPATIBLE)
            .addParameter(ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(Object.class)), "type")
            .returns(Boolean.TYPE)
            .addCode(builder.build())
            .build();
}
项目:aws-sdk-java-v2    文件:QueryXmlProtocolSpec.java   
@Override
public MethodSpec initProtocolFactory(IntermediateModel model) {
    MethodSpec.Builder methodSpec = MethodSpec.methodBuilder("init")
                                              .returns(listOfUnmarshallersType)
                                              .addModifiers(Modifier.PRIVATE);

    methodSpec.addStatement("$T<$T> unmarshallers = new $T<>()", List.class, unmarshallerType, ArrayList.class);
    errorUnmarshallers(model).forEach(methodSpec::addCode);
    methodSpec.addCode(CodeBlock.builder().add("unmarshallers.add(new $T($T.class));",
                                               getErrorUnmarshallerClass(model),
                                               poetExtensions.getModelClass(model.getSdkModeledExceptionBaseClassName()))
                                .build());
    methodSpec.addStatement("return $N", "unmarshallers");

    return methodSpec.build();
}
项目:GitHub    文件:ProcessorUtil.java   
private CodeBlock generateSeeMethodJavadocInternal(
    TypeName nameOfClassContainingMethod, String methodName,
    List<Object> safeParameterNames) {
   String javadocString = "@see $T#$L(";
  List<Object> javadocArgs = new ArrayList<>();
  javadocArgs.add(nameOfClassContainingMethod);
  javadocArgs.add(methodName);

  for (Object param : safeParameterNames) {
    javadocString += "$T, ";
    javadocArgs.add(param);
  }
  if (javadocArgs.size() > 2) {
    javadocString = javadocString.substring(0, javadocString.length() - 2);
  }
  javadocString += ")\n";
  return CodeBlock.of(javadocString, javadocArgs.toArray(new Object[0]));
}
项目:GitHub    文件:RequestOptionsGenerator.java   
private MethodSpec generateRequestOptionOverride(ExecutableElement methodToOverride) {
  return MethodSpec.overriding(methodToOverride)
      .returns(glideOptionsName)
      .addCode(CodeBlock.builder()
          .add("return ($T) super.$N(", glideOptionsName, methodToOverride.getSimpleName())
          .add(FluentIterable.from(methodToOverride.getParameters())
              .transform(new Function<VariableElement, String>() {
                @Override
                public String apply(VariableElement input) {
                  return input.getSimpleName().toString();
                }
              })
              .join(Joiner.on(", ")))
          .add(");\n")
          .build())
      .build();
}
项目:GitHub    文件:ProcessorUtil.java   
private CodeBlock generateSeeMethodJavadocInternal(
    TypeName nameOfClassContainingMethod, String methodName,
    List<Object> safeParameterNames) {
  StringBuilder javadocString = new StringBuilder("@see $T#$L(");
  List<Object> javadocArgs = new ArrayList<>();
  javadocArgs.add(nameOfClassContainingMethod);
  javadocArgs.add(methodName);

  for (Object param : safeParameterNames) {
    javadocString.append("$T, ");
    javadocArgs.add(param);
  }
  if (javadocArgs.size() > 2) {
    javadocString = new StringBuilder(javadocString.substring(0, javadocString.length() - 2));
  }
  javadocString.append(")\n");
  return CodeBlock.of(javadocString.toString(), javadocArgs.toArray(new Object[0]));
}
项目:aws-sdk-java-v2    文件:JsonProtocolSpec.java   
@Override
public CodeBlock responseHandler(OperationModel opModel) {
    ClassName unmarshaller = poetExtensions.getTransformClass(opModel.getReturnType().getReturnType() + "Unmarshaller");
    ClassName returnType = poetExtensions.getModelClass(opModel.getReturnType().getReturnType());

    return CodeBlock
            .builder()
            .add("\n\n$T<$T> responseHandler = $L.createResponseHandler(new $T()" +
                 "                                   .withPayloadJson($L)" +
                 "                                   .withHasStreamingSuccessResponse($L), new $T());",
                 HttpResponseHandler.class,
                 returnType,
                 "protocolFactory",
                 JsonOperationMetadata.class,
                 !opModel.getHasBlobMemberAsPayload(),
                 opModel.hasStreamingOutput(),
                 unmarshaller)
            .build();
}
项目:lazythreetenbp    文件:JavaWriter.java   
private FieldSpec regionId(Set<String> allRegionIds) {
    CodeBlock.Builder builder = CodeBlock.builder()
            .add("$T.asList(\n$>$>", Arrays.class);
    Iterator<String> iterator = allRegionIds.iterator();
    while (iterator.hasNext()) {
        builder.add("$S", iterator.next());
        if (iterator.hasNext()) {
            builder.add(",\n");
        }
    }
    builder.add("$<$<)");
    TypeName listType = ParameterizedTypeName.get(List.class, String.class);
    return FieldSpec.builder(listType, "REGION_IDS", STATIC, FINAL)
            .initializer(builder.build())
            .build();
}
项目:data-mediator    文件:SharedPropertiesNGenerator.java   
public static boolean generateSharedProperties(Collection<FieldData> fields,
                                               Elements elements, Filer filer, ProcessorPrinter pp){
    final ClassName cn_sp = ClassName.get(PKG_DM_INTERNAL, SIMPLE_NAME_SHARED_PROP);
    CodeBlock.Builder staticBuilder = CodeBlock.builder();
    for(FieldData fd : fields){
        staticBuilder.add("$T.putToCache($S, $S, $L);\n", cn_sp, fd.getTypeCompat().toString(),
                fd.getPropertyName(), fd.getComplexType());
    }
    String classSimpleName = SIMPLE_NAME_SHARED_PROP + "_" + findBestIndex(elements);
    TypeSpec typeSpec = TypeSpec.classBuilder(classSimpleName)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addStaticBlock(staticBuilder.build())
            .addJavadoc(CodeBlock.of(DOC))
            .build();

    try {
        JavaFile javaFile = JavaFile.builder(PKG_DM_INTERNAL, typeSpec)
                .build();
       // System.out.println(javaFile.toString());
        javaFile.writeTo(filer);
    } catch (IOException e) {
        pp.error(TAG, "generateSharedProperties", Util.toString(e));
        return false;
    }
    return true;
}
项目:LifecycleAware    文件:MethodWrapperGenerator.java   
private CodeBlock warningComment() {
    // This warning comment exists because it doesn't look like we can use reflection
    // before compilation to determine if the Annotated element actually has
    // the expected method. If the developer runs the annotation processor and the method
    // actually doesn't exist, they will see this comment right above the generated code to
    // hopefully guide them in the correct direction.
    final String elementVarName = Utils.tryToExtractClassName(typeUtils, annotatedElement);
    final String expectedMethod = annotatedElement.getAnnotation(LifecycleAware.class).method();
    return CodeBlock.builder()
            .add("/*\n")
            .add("* This will have a problem compiling if the method $L::$L()\n", elementVarName, expectedMethod)
            .add("* 1. does not exist.\n")
            .add("* 2. is not visible.\n")
            .add("*/\n")
            .build();
}
项目:LifecycleAware    文件:TargetBinderGenerator.java   
/**
 * Returns the element formatted as a code block if the element is an observer.
 * If the element is not an observer, wrap it in an observer and return that instead.
 *
 * @param element
 * @return
 */
private CodeBlock wrapObserverIfNecessary(Element element) {
    boolean needsWrapper = !Utils.implementsInterface(elementUtils, typeUtils, element, LifecycleAwareObserver.class);
    if (needsWrapper) {
        return CodeBlock.builder()
                .add("new $T($L.$L)",
                        wrappedProducer.getClassName(element),
                        PARAM_NAME_TARGET,
                        element.getSimpleName())
                .build();
    } else {
        return CodeBlock.builder()
                .add("$L.$L", PARAM_NAME_TARGET, element.getSimpleName())
                .build();
    }
}
项目:KiiAnnotation    文件:BuilderGenerator.java   
public static MethodSpec builderGroupBuild(ClassName className, List<MethodSpec> methodSpecList, List<FieldSpec> fieldSpecList) {
    String name = className.simpleName();
    CodeBlock.Builder codeBlock = CodeBlock.builder();

    for (int i = 0; i < methodSpecList.size(); i++) {
        codeBlock.add("$N.$N(this.$N);\n", name.toLowerCase(), methodSpecList.get(i).name, fieldSpecList.get(i).name);
    }

    return MethodSpec
            .methodBuilder("build")
            .addModifiers(Modifier.PUBLIC)
            .addStatement("$N $N = new $N($N)", name, name.toLowerCase(), name, "this.kiiGroup")
            .addCode(codeBlock.build())
            .returns(className)
            .addStatement("return $N", name.toLowerCase())
            .build();
}
项目:convalida    文件:JavaFiler.java   
private static void createNotEmptyValidationCodeBlock(MethodSpec.Builder constructorBuilder, ValidationField validationField) {
    CodeBlock notEmptyValidationCodeBlock = CodeBlock.builder()
            .add("\n")
            .add("{")
            .add("\n")
            .indent()
            .add(createElementDeclarationCode(validationField))
            .add(createErrorMessageDeclarationCode(validationField.getId()))
            .addStatement(
                    "this.$N.addValidator(new $T($N, $N))",
                    "validationSet",
                    Constants.NOT_EMPTY_VALIDATOR,
                    validationField.getName(),
                    "errorMessage"
            )
            .unindent()
            .add("}")
            .add("\n")
            .build();

    constructorBuilder.addCode(notEmptyValidationCodeBlock);
}
项目:arez    文件:ComponentDescriptor.java   
/**
 * Generate the isDisposed method.
 */
@Nonnull
private MethodSpec buildIsDisposed()
  throws ArezProcessorException
{
  final MethodSpec.Builder builder =
    MethodSpec.methodBuilder( "isDisposed" ).
      addModifiers( Modifier.PUBLIC ).
      addAnnotation( Override.class ).
      returns( TypeName.BOOLEAN );

  final CodeBlock.Builder block = CodeBlock.builder();
  block.beginControlFlow( "if ( $N().isTransactionActive() && !this.$N.isDisposed() ) ",
                          getContextMethodName(),
                          GeneratorUtil.DISPOSED_OBSERVABLE_FIELD_NAME );
  block.addStatement( "this.$N.reportObserved()", GeneratorUtil.DISPOSED_OBSERVABLE_FIELD_NAME );
  block.addStatement( "return this.$N", GeneratorUtil.DISPOSED_FIELD_NAME );
  block.nextControlFlow( "else" );
  block.addStatement( "return this.$N", GeneratorUtil.DISPOSED_FIELD_NAME );
  block.endControlFlow();
  builder.addCode( block.build() );

  return builder.build();
}
项目:Spyglass    文件:SpecificValueIsAvailableMethodGenerator.java   
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
    return CodeBlock
            .builder()
            .addStatement(
                    "final boolean defaultConsistentlyReturned = \n" +
                            "$1N().getInt($2L, 1) == 1 && \n" +
                            "$1N().getInt($2L, 2) == 2",
                    CallerDef.GET_ATTRS,
                    getLiteralFromAnnotation(object, "attributeId"))
            .add("\n")
            .addStatement(
                    "return defaultConsistentlyReturned ? \n" +
                            "false : \n" +
                            "($N().getInt($L, 0) & $L) > 0",
                    CallerDef.GET_ATTRS,
                    getLiteralFromAnnotation(object, "attributeId"),
                    getLiteralFromAnnotation(object, "handledFlags"))
            .build();
}
项目:Spyglass    文件:SpecificValueIsAvailableMethodGenerator.java   
@Override
public CodeBlock supplyFor(final AnnotationMirror object) {
    return CodeBlock
            .builder()
            .addStatement(
                    "final boolean defaultConsistentlyReturned = \n" +
                            "$1N().getBoolean($2L, true) == true && \n" +
                            "$1N().getBoolean($2L, false) == false",
                    CallerDef.GET_ATTRS,
                    getLiteralFromAnnotation(object, "attributeId"))
            .add("\n")
            .addStatement(
                    "return defaultConsistentlyReturned ? \n" +
                            "false : \n" +
                            "$N().getBoolean($L, true) == $L",
                    CallerDef.GET_ATTRS,
                    getLiteralFromAnnotation(object, "attributeId"),
                    getLiteralFromAnnotation(object, "handledBoolean"))
            .build();
}
项目:KiiAnnotation    文件:BuilderGenerator.java   
public static MethodSpec builderBuild(ClassName className, List<MethodSpec> methodSpecList, List<FieldSpec> fieldSpecList) {
    String name = className.simpleName();
    CodeBlock.Builder codeBlock = CodeBlock.builder();

    for (int i = 0; i < methodSpecList.size(); i++) {
        codeBlock.add("$N.$N(this.$N);\n", name.toLowerCase(), methodSpecList.get(i).name, fieldSpecList.get(i).name);
    }

    return MethodSpec
            .methodBuilder("build")
            .addModifiers(Modifier.PUBLIC)
            .addStatement("$N $N = new $N()", name, name.toLowerCase(), name)
            .addCode(codeBlock.build())
            .returns(className)
            .addStatement("return $N", name.toLowerCase())
            .build();
}
项目:Spyglass    文件:CastWrapperGenerator.java   
public CodeBlock generateFor(final MethodSpec method, final TypeMirror recipient) {
    final TypeMirror methodReturnType = elementHelper.getTypeElement(method.returnType.toString()).asType();

    if (typeMirrorHelper.isNumber(recipient) && typeMirrorHelper.isNumber(methodReturnType)) {
        return generateNumberCastWrapperFor(method, recipient);

    } else if (typeMirrorHelper.isCharacter(recipient) && typeMirrorHelper.isCharacter(methodReturnType)) {
        return generateCharacterCastWrapperFor(method, recipient);

    } else {
        return CodeBlock
                .builder()
                .add("($T) $N()", recipient, method)
                .build();
    }
}
项目:Spyglass    文件:GetDefaultMethodGenerator.java   
@Override
public MethodSpec supplyFor(final AnnotationMirror anno) {
    final CodeBlock body = CodeBlock
            .builder()
            .addStatement(
                    "return $T.getColorStateList($N(), $L)",
                    AndroidClassNames.CONTEXT_COMPAT,
                    CallerDef.GET_CONTEXT,
                    getLiteralFromAnnotation(anno, "resId"))
            .build();

    return getBaseMethodSpec()
            .returns(AndroidClassNames.COLOR_STATE_LIST)
            .addCode(body)
            .build();
}
项目:auto-value-bundle    文件:GsonDeserializer.java   
@Override
public String deserializeUnknownParameterizedObject(
        String readFromBundle,
        ParameterizedTypeName parameterizedTypeName,
        VariableElement deserializerElement) {
    StringBuilder typeToken = new StringBuilder("new ")
            .append(TYPE_TOKEN_FULLY_QUALIFIED)
            .append("<")
            .append(parameterizedTypeName.rawType.simpleName())
            .append("<");
    for (TypeName typeName : parameterizedTypeName.typeArguments) {
        typeToken.append(deserializeParameterizedObject(typeName))
                .append(", ");
    }
    typeToken.deleteCharAt(typeToken.length() - 1);
    typeToken.deleteCharAt(typeToken.length() - 1);

    typeToken.append(">(){}.getType()");

    return CodeBlock.builder()
            .add("$L.$L($L, $L)", deserializerElement.getSimpleName().toString(), "fromJson", readFromBundle,
                    typeToken)
            .build()
            .toString();
}
项目:aws-sdk-java-v2    文件:JsonProtocolSpec.java   
@Override
public List<CodeBlock> errorUnmarshallers(IntermediateModel model) {
    List<ShapeModel> exceptions = model.getShapes().values().stream()
                                       .filter(s -> s.getShapeType().equals(ShapeType.Exception))
                                       .collect(Collectors.toList());

    return exceptions.stream().map(s -> {
        ClassName exceptionClass = poetExtensions.getModelClass(s.getShapeName());
        return CodeBlock.builder().add(".addErrorMetadata(new $T().withErrorCode($S).withModeledClass($T.class))",
                                       JsonErrorShapeMetadata.class,
                                       s.getErrorCode(),
                                       exceptionClass)
                        .build();
    }).collect(Collectors.toList());
}
项目:GitHub    文件:FieldDrawableBinding.java   
@Override public CodeBlock render(int sdk) {
  if (tintAttributeId.value != 0) {
    return CodeBlock.of("target.$L = $T.getTintedDrawable(context, $L, $L)", name, UTILS, id.code,
        tintAttributeId.code);
  }
  if (sdk >= 21) {
    return CodeBlock.of("target.$L = context.getDrawable($L)", name, id.code);
  }
  return CodeBlock.of("target.$L = $T.getDrawable(context, $L)", name, CONTEXT_COMPAT, id.code);
}
项目:Spyglass    文件:GetDefaultMethodGenerator.java   
@Override
public MethodSpec supplyFor(final AnnotationMirror anno) {
    final CodeBlock body = CodeBlock
            .builder()
            .addStatement("return $L", getLiteralFromAnnotation(anno, "value"))
            .build();

    return getBaseMethodSpec()
            .returns(String.class)
            .addCode(body)
            .build();
}
项目:GitHub    文件:Id.java   
Id(int value, ClassName className, String resourceName) {
  this.value = value;
  this.code = className.topLevelClassName().equals(ANDROID_R)
    ? CodeBlock.of("$L.$N", className, resourceName)
    : CodeBlock.of("$T.$N", className, resourceName);
  this.qualifed = true;
}
项目:arez    文件:ComponentDescriptor.java   
@Nonnull
private MethodSpec buildEqualsMethod()
  throws ArezProcessorException
{
  final String idMethod =
    null == _componentId ? GeneratorUtil.ID_FIELD_NAME : _componentId.getSimpleName().toString();

  final MethodSpec.Builder method =
    MethodSpec.methodBuilder( "equals" ).
      addModifiers( Modifier.PUBLIC, Modifier.FINAL ).
      addAnnotation( Override.class ).
      addParameter( Object.class, "o", Modifier.FINAL ).
      returns( TypeName.BOOLEAN );

  final ClassName generatedClass = ClassName.get( getPackageName(), getArezClassName() );

  final CodeBlock.Builder codeBlock = CodeBlock.builder();
  codeBlock.beginControlFlow( "if ( this == o )" );
  codeBlock.addStatement( "return true" );
  codeBlock.nextControlFlow( "else if ( null == o || !(o instanceof $T) )", generatedClass );
  codeBlock.addStatement( "return false" );
  codeBlock.nextControlFlow( "else" );
  codeBlock.addStatement( "final $T that = ($T) o;", generatedClass, generatedClass );
  final TypeKind kind = null != _componentId ? _componentId.getReturnType().getKind() : TypeKind.LONG;
  if ( kind == TypeKind.DECLARED || kind == TypeKind.TYPEVAR )
  {
    codeBlock.addStatement( "return null != $N() && $N().equals( that.$N() )", idMethod, idMethod, idMethod );
  }
  else
  {
    codeBlock.addStatement( "return $N() == that.$N()", idMethod, idMethod );
  }
  codeBlock.endControlFlow();
  method.addCode( codeBlock.build() );
  return method.build();
}
项目:GitHub    文件:RequestManagerGenerator.java   
/**
 * Generates overrides of existing RequestManager methods so that they return our generated
 * RequestBuilder subtype.
 */
private MethodSpec generateRequestManagerMethodOverride(ExecutableElement methodToOverride) {
   // We've already verified that this method returns a RequestBuilder and RequestBuilders have
  // exactly one type argument, so this is safe unless those assumptions change.
  TypeMirror typeArgument =
      ((DeclaredType) methodToOverride.getReturnType()).getTypeArguments().get(0);

  ParameterizedTypeName generatedRequestBuilderOfType =
      ParameterizedTypeName.get(generatedRequestBuilderClassName, ClassName.get(typeArgument));

  return MethodSpec.overriding(methodToOverride)
      .returns(generatedRequestBuilderOfType)
      .addCode(CodeBlock.builder()
          .add("return ($T) super.$N(",
              generatedRequestBuilderOfType, methodToOverride.getSimpleName())
          .add(FluentIterable.from(methodToOverride.getParameters())
              .transform(new Function<VariableElement, String>() {
                @Override
                public String apply(VariableElement input) {
                  return input.getSimpleName().toString();
                }
              })
              .join(Joiner.on(", ")))
          .add(");\n")
          .build())
      .build();
}
项目:aws-sdk-java-v2    文件:PaginatorResponseClassSpec.java   
private MethodSpec getMethodsSpecForSingleResultKey(String resultKey) {
    TypeName resultKeyType = getTypeForResultKey(resultKey);
    MemberModel resultKeyModel = memberModelForResponseMember(resultKey);

    return MethodSpec.methodBuilder(resultKeyModel.getFluentGetterMethodName())
                     .addModifiers(Modifier.PUBLIC)
                     .returns(ParameterizedTypeName.get(ClassName.get(SdkIterable.class), resultKeyType))
                     .addCode("$T getIterator = ",
                              ParameterizedTypeName.get(ClassName.get(Function.class),
                                                        responseType(),
                                                        ParameterizedTypeName.get(ClassName.get(Iterator.class),
                                                                                  resultKeyType)))
                     .addCode(getPaginatedMemberIteratorLambdaBlock(resultKey, resultKeyModel))
                     .addCode("\n")
                     .addStatement("return new $T(this, getIterator)", PaginatedItemsIterable.class)
                     .addJavadoc(CodeBlock.builder()
                                          .add("Returns an iterable to iterate through the paginated {@link $T#$L()} member. "
                                               + "The returned iterable is used to iterate through the results across all "
                                               + "response pages and not a single page.\n",
                                               responseType(), resultKeyModel.getFluentGetterMethodName())
                                          .add("\n")
                                          .add("This method is useful if you are interested in iterating over the paginated "
                                               + "member in the response pages instead of the top level pages. "
                                               + "Similar to iteration over pages, this method internally makes service "
                                               + "calls to get the next list of results until the iteration stops or "
                                               + "there are no more results.")
                                          .build())
                     .build();
}
项目:aws-sdk-java-v2    文件:PaginationDocs.java   
private CodeBlock buildCode(CodeBlock codeSnippet) {
    return CodeBlock.builder()
                    .add("<pre>{@code\n")
                    .add(codeSnippet)
                    .add("}</pre>")
                    .build();

}
项目:butterknife-parent    文件:FieldDrawableBinding.java   
@Override public CodeBlock render(int sdk) {
  if (tintAttributeId.value != 0) {
    return CodeBlock.of("target.$L = $T.getTintedDrawable(context, $L, $L)", name, UTILS, id.code,
        tintAttributeId.code);
  }
  if (sdk >= 21) {
    return CodeBlock.of("target.$L = context.getDrawable($L)", name, id.code);
  }
  return CodeBlock.of("target.$L = $T.getDrawable(context, $L)", name, CONTEXT_COMPAT, id.code);
}
项目:aws-sdk-java-v2    文件:PoetCollectorsTest.java   
@Test
public void delimitedCodeBlocksJoined() {
    CodeBlock a = CodeBlock.of("a");
    CodeBlock b = CodeBlock.of("b");
    CodeBlock delimeter = CodeBlock.of(",");
    CodeBlock ab = CodeBlock.builder().add(a).add(delimeter).add(b).build();

    CodeBlock result = Stream.of(a, b).collect(PoetCollectors.toDelimitedCodeBlock(","));
    assertThat(result).isEqualTo(ab);
}
项目:aws-sdk-java-v2    文件:JsonProtocolSpec.java   
@Override
public CodeBlock errorResponseHandler(OperationModel opModel) {
    return CodeBlock
            .builder()
            .add("\n\n$T<$T> errorResponseHandler = createErrorResponseHandler();",
                 HttpResponseHandler.class, SdkServiceException.class)
            .build();
}
项目:Spyglass    文件:TestCallerGenerator.java   
@Test
public void testGenerateFor_elementWithValueHandlerButNoDefault() {
    final ExecutableElement element = avatarRule.getElementWithUniqueId("value handler no default");

    final TypeSpec result = callerGenerator.generateFor(
            element,
            CodeBlock.of("target"),
            CodeBlock.of("context"),
            CodeBlock.of("attrs"));

    assertThat(result, is(notNullValue()));
    checkCompiles(result);
}
项目:ActivityBuilder    文件:BuilderUtilGenerator.java   
private void addBuilderToMap(CodeBlock.Builder block, TypeElement activity) {
  PackageElement pack = getElements().getPackageOf(activity);
  ClassName builder =
      ClassName.get(pack.getQualifiedName().toString(), activity.getSimpleName() + "Builder");
  ClassName activityName = ClassName.get(activity);
  block.addStatement("sBuilderMap.put($T.class,$T.class)", activityName, builder);
}
项目:LifecycleAware    文件:TargetBinderGenerator.java   
private CodeBlock observerStatement(Element element) {
    final String lifecycleBindMethod = "addObserver";

    return CodeBlock.builder()
            .addStatement("$L.$L(new $T($L))",
                    PARAM_NAME_LIFECYCLE,
                    lifecycleBindMethod,
                    lifecycleObserverProducer.getClassName(element),
                    wrapObserverIfNecessary(element))
            .build();
}
项目:r-parser    文件:Id.java   
Id(int value, ClassName className, String resourceName) {
    this.value = value;
    this.code = className.topLevelClassName().equals(ANDROID_R)
            ? CodeBlock.of("$L.$N", className, resourceName)
            : CodeBlock.of("$T.$N", className, resourceName);
    this.qualifed = true;
}
项目:convalida    文件:JavaFiler.java   
private static void createLengthValidationCodeBlock(MethodSpec.Builder constructorBuilder, ValidationField validationField) {
    int minLength = validationField.getElement().getAnnotation(LengthValidation.class).min();
    int maxLength = validationField.getElement().getAnnotation(LengthValidation.class).max();
    CodeBlock lengthValidationCodeBlock = CodeBlock.builder()
            .add("\n")
            .add("{")
            .add("\n")
            .indent()
            .add(createElementDeclarationCode(validationField))
            .addStatement("int minLength = $L", minLength)
            .addStatement("int maxLength = $L", maxLength)
            .add(createErrorMessageDeclarationCode(validationField.getId()))
            .addStatement(
                    "this.$N.addValidator(new $T($N, $N, $N, $N))",
                    "validationSet",
                    Constants.LENGTH_VALIDATOR,
                    validationField.getName(),
                    "minLength",
                    "maxLength",
                    "errorMessage"
            )
            .unindent()
            .add("}")
            .add("\n")
            .build();

    constructorBuilder.addCode(lengthValidationCodeBlock);
}
项目:zerocell    文件:CellMethodSpec.java   
public static MethodSpec build(List<ColumnInfoType> columns) {
    final CodeBlock.Builder builder = CodeBlock.builder();
    LoggerFactory.getLogger(ZeroCellAnnotationProcessor.class)
                 .info("Found {} columns in source class", columns.size());
    columns.forEach(column -> {
        String staticFieldName = "COL_" + column.getName();
        String fieldName = column.getFieldName();

        String beanSetterProperty = beanSetterPropertyName(fieldName);

        builder.beginControlFlow("if ($L == column)", staticFieldName)
            .addStatement("assertColumnName($S, formattedValue)", column.getName());

        converterStatementFor(builder, column, beanSetterProperty);

        builder.addStatement("return").endControlFlow();
    });

    return  MethodSpec.methodBuilder("cell")
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC)
            .addParameter(String.class, "cellReference")
            .addParameter(String.class, "formattedValue", Modifier.FINAL)
            .addParameter(XSSFComment.class, "xssfComment", Modifier.FINAL)
            .addStatement("if (java.util.Objects.isNull(cur)) return")
            .addComment("Gracefully handle missing CellRef here in a similar way as XSSFCell does")
            .beginControlFlow("if(cellReference == null)")
            .addStatement("cellReference = new $T(currentRow, currentCol).formatAsString()", org.apache.poi.ss.util.CellAddress.class)
            .endControlFlow()
            .addStatement("int column = new $T(cellReference).getCol()", org.apache.poi.hssf.util.CellReference.class)
            .addStatement("currentCol = column")
            .addCode(builder.build())
            .build();
}
项目:convalida    文件:JavaFiler.java   
private static CodeBlock createElementDeclarationCode(ValidationField validationField) {
    return CodeBlock.builder()
            .addStatement(
                    "$T $N = $N.$N",
                    validationField.getTypeName(),
                    validationField.getName(),
                    "target",
                    validationField.getName()
            )
            .build();
}
项目:Spyglass    文件:TestCallerGenerator.java   
@Test
public void testGenerateFor_elementWithValueHandlerAndDefault() {
    final ExecutableElement element = avatarRule.getElementWithUniqueId("value handler with default");

    final TypeSpec result = callerGenerator.generateFor(
            element,
            CodeBlock.of("target"),
            CodeBlock.of("context"),
            CodeBlock.of("attrs"));

    assertThat(result, is(notNullValue()));
    checkCompiles(result);
}
项目:Spyglass    文件:GetPlaceholderMethodGenerator.java   
@Override
public MethodSpec supplyFor(final AnnotationMirror useAnno, final int position) {
    final AnnotationValue rawValue = annoMirrorHelper.getValueUsingDefaults(useAnno, "value");

    return getBaseMethodSpec(position)
            .returns(Character.class)
            .addCode(CodeBlock
                    .builder()
                    .addStatement("return ($T) $L", Character.class, rawValue.toString())
                    .build())
            .build();
}
项目:Spyglass    文件:CallerDef.java   
public static MethodSpec.Builder getNewConstructorPrototype(final TypeName targetType) {
    return MethodSpec
            .constructorBuilder()
            .addModifiers(PUBLIC)
            .addParameter(targetType, "target", FINAL)
            .addParameter(AndroidClassNames.CONTEXT, "context", FINAL)
            .addParameter(AndroidClassNames.TYPED_ARRAY, "attrs", FINAL)
            .addCode(CodeBlock
                    .builder()
                    .addStatement("super(target, context, attrs)")
                    .build());
}