當前位置: 首頁>>代碼示例>>Java>>正文


Java CodeBlock類代碼示例

本文整理匯總了Java中com.squareup.javapoet.CodeBlock的典型用法代碼示例。如果您正苦於以下問題:Java CodeBlock類的具體用法?Java CodeBlock怎麽用?Java CodeBlock使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


CodeBlock類屬於com.squareup.javapoet包,在下文中一共展示了CodeBlock類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: generateSeeMethodJavadocInternal

import com.squareup.javapoet.CodeBlock; //導入依賴的package包/類
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]));
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:19,代碼來源:ProcessorUtil.java

示例2: createIsJsObject

import com.squareup.javapoet.CodeBlock; //導入依賴的package包/類
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();
}
 
開發者ID:codegen-io,項目名稱:jso-builder,代碼行數:23,代碼來源:SerializerGenerator.java

示例3: initProtocolFactory

import com.squareup.javapoet.CodeBlock; //導入依賴的package包/類
@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();
}
 
開發者ID:aws,項目名稱:aws-sdk-java-v2,代碼行數:17,代碼來源:QueryXmlProtocolSpec.java

示例4: generateSeeMethodJavadocInternal

import com.squareup.javapoet.CodeBlock; //導入依賴的package包/類
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]));
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:19,代碼來源:ProcessorUtil.java

示例5: generateRequestOptionOverride

import com.squareup.javapoet.CodeBlock; //導入依賴的package包/類
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();
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:18,代碼來源:RequestOptionsGenerator.java

示例6: responseHandler

import com.squareup.javapoet.CodeBlock; //導入依賴的package包/類
@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();
}
 
開發者ID:aws,項目名稱:aws-sdk-java-v2,代碼行數:20,代碼來源:JsonProtocolSpec.java

示例7: regionId

import com.squareup.javapoet.CodeBlock; //導入依賴的package包/類
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();
}
 
開發者ID:gabrielittner,項目名稱:lazythreetenbp,代碼行數:17,代碼來源:JavaWriter.java

示例8: generateSharedProperties

import com.squareup.javapoet.CodeBlock; //導入依賴的package包/類
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;
}
 
開發者ID:LightSun,項目名稱:data-mediator,代碼行數:27,代碼來源:SharedPropertiesNGenerator.java

示例9: warningComment

import com.squareup.javapoet.CodeBlock; //導入依賴的package包/類
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();
}
 
開發者ID:jzallas,項目名稱:LifecycleAware,代碼行數:17,代碼來源:MethodWrapperGenerator.java

示例10: wrapObserverIfNecessary

import com.squareup.javapoet.CodeBlock; //導入依賴的package包/類
/**
 * 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();
    }
}
 
開發者ID:jzallas,項目名稱:LifecycleAware,代碼行數:23,代碼來源:TargetBinderGenerator.java

示例11: builderGroupBuild

import com.squareup.javapoet.CodeBlock; //導入依賴的package包/類
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();
}
 
開發者ID:daisuke-nomura,項目名稱:KiiAnnotation,代碼行數:18,代碼來源:BuilderGenerator.java

示例12: createNotEmptyValidationCodeBlock

import com.squareup.javapoet.CodeBlock; //導入依賴的package包/類
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);
}
 
開發者ID:WellingtonCosta,項目名稱:convalida,代碼行數:23,代碼來源:JavaFiler.java

示例13: buildIsDisposed

import com.squareup.javapoet.CodeBlock; //導入依賴的package包/類
/**
 * 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();
}
 
開發者ID:arez,項目名稱:arez,代碼行數:27,代碼來源:ComponentDescriptor.java

示例14: supplyFor

import com.squareup.javapoet.CodeBlock; //導入依賴的package包/類
@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();
}
 
開發者ID:MatthewTamlin,項目名稱:Spyglass,代碼行數:21,代碼來源:SpecificValueIsAvailableMethodGenerator.java

示例15: builderBuild

import com.squareup.javapoet.CodeBlock; //導入依賴的package包/類
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();
}
 
開發者ID:daisuke-nomura,項目名稱:KiiAnnotation,代碼行數:18,代碼來源:BuilderGenerator.java


注:本文中的com.squareup.javapoet.CodeBlock類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。