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


Java CodeBlock.Builder方法代碼示例

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


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

示例1: createNewObject

import com.squareup.javapoet.CodeBlock; //導入方法依賴的package包/類
private CodeBlock createNewObject() {
    CodeBlock.Builder codeBlockBuilder = CodeBlock.builder();
    codeBlockBuilder.add("return new $N(", descriptor.getTypeElement().getSimpleName());
    StringBuilder stringBuilder = new StringBuilder();

    List<VariableElement> elements = descriptor.getFields();

    for (int i = 0; i < elements.size(); i++) {

        VariableElement variableElement = elements.get(i);
        if (checkIfFieldForProcessing(variableElement)) {
            continue;
        }

        stringBuilder.append(String.format("%s,", variableElement.getSimpleName().toString()));
    }

    int last = stringBuilder.lastIndexOf(",");
    codeBlockBuilder.add(stringBuilder.deleteCharAt(last).toString());
    codeBlockBuilder.add(");\n");

    return codeBlockBuilder.build();
}
 
開發者ID:rsulkowski,項目名稱:jdoocsoup,代碼行數:24,代碼來源:DataClassBuilderHandler.java

示例2: 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

示例3: render

import com.squareup.javapoet.CodeBlock; //導入方法依賴的package包/類
CodeBlock render() {
  CodeBlock.Builder builder = CodeBlock.builder()
      .add("target.$L = $T.$L(", name, UTILS, kind.factoryName);
  for (int i = 0; i < ids.size(); i++) {
    if (i > 0) {
      builder.add(", ");
    }
    builder.add("\n");

    boolean requiresCast = requiresCast(type);
    if (!requiresCast && !required) {
      builder.add("source.findViewById($L)", ids.get(i).code);
    } else {
      builder.add("$T.find", UTILS);
      builder.add(required ? "RequiredView" : "OptionalView");
      if (requiresCast) {
        builder.add("AsType");
      }
      builder.add("(source, $L, \"field '$L'\"", ids.get(i).code, name);
      if (requiresCast) {
        TypeName rawType = type;
        if (rawType instanceof ParameterizedTypeName) {
          rawType = ((ParameterizedTypeName) rawType).rawType;
        }
        builder.add(", $T.class", rawType);
      }
      builder.add(")");
    }
  }
  return builder.add(")").build();
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:32,代碼來源:FieldCollectionViewBinding.java

示例4: writeVersion

import com.squareup.javapoet.CodeBlock; //導入方法依賴的package包/類
public static CodeBlock writeVersion(int version, ParameterSpec out) {
    CodeBlock.Builder block = CodeBlock.builder();

    block.add("$N.writeInt( /* version */ " + version + ")", out);
    block.add(";\n");

    return block.build();
}
 
開發者ID:foodora,項目名稱:android-auto-mapper,代碼行數:9,代碼來源:Parcelables.java

示例5: generate

import com.squareup.javapoet.CodeBlock; //導入方法依賴的package包/類
@Override protected TypeSpec generate() {
  TypeSpec.Builder builder = TypeSpec.classBuilder("BuilderUtil")
      .addModifiers(Modifier.PUBLIC)
      .addField(FieldSpec.builder(
          ParameterizedTypeName.get(ClassName.get(HashMap.class),
              ParameterizedTypeName.get(ClassName.get(Class.class),
                  WildcardTypeName.subtypeOf(Activity.class)),
              ParameterizedTypeName.get(ClassName.get(Class.class),
                  WildcardTypeName.subtypeOf(ClassName.get(baseActivityBuilder)))
          ), "sBuilderMap")
          .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
          .initializer("new $T<>()", HashMap.class)
          .build());

  MethodSpec createBuilder = buildCreateBuilder();
  builder.addMethod(createBuilder)
      .addMethod(buildCreateBuilderWithIntent())
      .addMethod(buildSmallCreate(createBuilder));

  CodeBlock.Builder mapIniter = CodeBlock.builder();

  for (TypeElement element : activityList) {
    addBuilderToMap(mapIniter, element);
    builder.addMethod(buildCreateHelper(element));
  }
  builder.addStaticBlock(mapIniter.build());
  return builder.build();
}
 
開發者ID:douo,項目名稱:ActivityBuilder,代碼行數:29,代碼來源:BuilderUtilGenerator.java

示例6: toCodeBlockBuilder

import com.squareup.javapoet.CodeBlock; //導入方法依賴的package包/類
/**
 * {@link Collector} used combine a {@link java.util.stream.Stream} of {@link CodeBlock}s into a single {@link CodeBlock}.
 *
 * @return
 */
public static Collector<CodeBlock, CodeBlock.Builder, CodeBlock.Builder> toCodeBlockBuilder() {
    return Collector.of(
            CodeBlock::builder,
            CodeBlock.Builder::add,
            (builder, builder2) -> builder.add(builder2.build())
    );
}
 
開發者ID:jzallas,項目名稱:LifecycleAware,代碼行數:13,代碼來源:Utils.java

示例7: generateGetProperties

import com.squareup.javapoet.CodeBlock; //導入方法依賴的package包/類
private static CodeBlock generateGetProperties(List<PropertyInfo> properties)
    throws ReactPropertyException {
  CodeBlock.Builder builder = CodeBlock.builder();
  for (PropertyInfo propertyInfo : properties) {
    try {
      String typeName = getPropertypTypeName(propertyInfo.mProperty, propertyInfo.propertyType);
      builder.addStatement("props.put($S, $S)", propertyInfo.mProperty.name(), typeName);
    } catch (IllegalArgumentException e) {
      throw new ReactPropertyException(e.getMessage(), propertyInfo);
    }
  }

  return builder.build();
}
 
開發者ID:qq565999484,項目名稱:RNLearn_Project1,代碼行數:15,代碼來源:ReactPropertyProcessor.java

示例8: readValueWithTypeAdapter

import com.squareup.javapoet.CodeBlock; //導入方法依賴的package包/類
public static void readValueWithTypeAdapter(CodeBlock.Builder block, AutoMappperProcessor.Property property, final FieldSpec adapter) {
    if (property.isNullable()) {
        block.add("in.readInt() == 0 ? ");
    }
    block.add("$N.fromParcel(in)", adapter);
    if (property.isNullable()) {
        block.add(" : null");
    }
}
 
開發者ID:foodora,項目名稱:android-auto-mapper,代碼行數:10,代碼來源:Parcelables.java

示例9: valueCodeBlock

import com.squareup.javapoet.CodeBlock; //導入方法依賴的package包/類
public static CodeBlock valueCodeBlock(ProcessingEnvironment env, TypeMirror t, Object value) {
    // try unbox so primitive types are handle by kind
    try { t = env.getTypeUtils().unboxedType(t); } catch (Exception ignore) {}

    CodeBlock.Builder block = CodeBlock.builder();
    switch (t.getKind()) {
        case BOOLEAN:
        case BYTE:
        case SHORT:
        case INT:
        case LONG:
        case FLOAT:
        case DOUBLE:
            block.add("$L", value);
            break;
        case CHAR:
            block.add("'$L'", value);
            break;
        case DECLARED:
            if (MoreTypes.isTypeOf(String.class, t)) {
                block.add("$S", value);
            } else if (isEnum(t)) {
                block.add("$T.$L", t, value);
            } else if (env.getTypeUtils().isSubtype(t, typeElementFor(env, Number.class).asType())) {
                block.add("$L", value);
            } else if (MoreTypes.isTypeOf(Class.class, t)) {
                block.add("$T.class", value);
            } else {
                block.add("$T.valueOf($S)", t, value);
            }
            break;
        default:
            throw new IllegalArgumentException("illegal property type " + t);
    }
    return block.build();
}
 
開發者ID:intendia-oss,項目名稱:qualifier,代碼行數:37,代碼來源:StaticQualifierMetamodelProcessor.java

示例10: codeBlockForCreate

import com.squareup.javapoet.CodeBlock; //導入方法依賴的package包/類
private CodeBlock codeBlockForCreate(final ClassName dataBindingClassName) {
    CodeBlock.Builder builder = CodeBlock.builder();

    builder.add("$T from = LayoutInflater.from(parent.getContext());\n", AndroidClassNames.INFLATER)
            .add("$1T binding = $2T.inflate(from, parent, false);\n", dataBindingClassName, dataBindingClassName)
            .add("$1T binder = new $2T(binding);\n", viewBinderClassName, viewBinderClassName)
            .add("return new AutoAdapterViewHolder<>(binding.getRoot(),binder,viewIds);\n").build();
    return builder.build();
}
 
開發者ID:renard314,項目名稱:auto-adapter,代碼行數:10,代碼來源:ViewHolderFactoryGenerator.java

示例11: addControlFlow

import com.squareup.javapoet.CodeBlock; //導入方法依賴的package包/類
private void addControlFlow(CodeBlock.Builder block,
    CodeBlock typeBlock,
    TypeName elementTypeName,
    int pos) {
  if (pos == 0) {
    block.beginControlFlow("if ($L.equals($T.class))", typeBlock, elementTypeName);
  } else {
    block.nextControlFlow("else if ($L.equals($T.class))", typeBlock, elementTypeName);
  }
}
 
開發者ID:hzsweers,項目名稱:inspector,代碼行數:11,代碼來源:InspectorFactoryProcessor.java

示例12: getCodeBlockForReactModuleInfos

import com.squareup.javapoet.CodeBlock; //導入方法依賴的package包/類
private CodeBlock getCodeBlockForReactModuleInfos(List<String> nativeModules)
  throws ReactModuleSpecException {
  CodeBlock.Builder builder = CodeBlock.builder();
  if (nativeModules == null || nativeModules.isEmpty()) {
    builder.addStatement("return Collections.emptyMap()");
  } else {
    builder.addStatement("$T map = new $T()", MAP_TYPE, INSTANTIATED_MAP_TYPE);

    for (String nativeModule : nativeModules) {
      String keyString = nativeModule + ".class";

      TypeElement typeElement = mElements.getTypeElement(nativeModule);
      if (typeElement == null) {
        throw new ReactModuleSpecException(
          keyString + " not found by ReactModuleSpecProcessor. " +
          "Did you misspell the module?");
      }
      ReactModule reactModule = typeElement.getAnnotation(ReactModule.class);
      if (reactModule == null) {
        throw new ReactModuleSpecException(
          keyString + " not found by ReactModuleSpecProcessor. " +
          "Did you forget to add the @ReactModule annotation to the native module?");
      }

      List<? extends Element> elements = typeElement.getEnclosedElements();
      boolean hasConstants = false;
      if (elements != null) {
        hasConstants = elements.stream()
          .anyMatch((Element m) -> m.getKind() == ElementKind.METHOD && m.getSimpleName().contentEquals("getConstants"));
      }

      String valueString = new StringBuilder()
        .append("new ReactModuleInfo(")
        .append("\"").append(reactModule.name()).append("\"").append(", ")
        .append(reactModule.canOverrideExistingModule()).append(", ")
        .append(reactModule.supportsWebWorkers()).append(", ")
        .append(reactModule.needsEagerInit()).append(", ")
        .append(hasConstants)
        .append(")")
        .toString();

      builder.addStatement("map.put(" + keyString + ", " + valueString + ")");
    }
    builder.addStatement("return map");
  }
  return builder.build();
}
 
開發者ID:qq565999484,項目名稱:RNLearn_Project1,代碼行數:48,代碼來源:ReactModuleSpecProcessor.java

示例13: getPropertyExtractor

import com.squareup.javapoet.CodeBlock; //導入方法依賴的package包/類
private static CodeBlock.Builder getPropertyExtractor(
    PropertyInfo info,
    CodeBlock.Builder builder) {
  TypeName propertyType = info.propertyType;
  if (propertyType.equals(STRING_TYPE)) {
    return builder.add("props.getString(name)");
  } else if (propertyType.equals(READABLE_ARRAY_TYPE)) {
    return builder.add("props.getArray(name)");
  } else if (propertyType.equals(READABLE_MAP_TYPE)) {
    return builder.add("props.getMap(name)");
  } else if (propertyType.equals(DYNAMIC_TYPE)) {
    return builder.add("props.getDynamic(name)");
  }

  if (BOXED_PRIMITIVES.contains(propertyType)) {
    propertyType = propertyType.unbox();
  }

  if (propertyType.equals(TypeName.BOOLEAN)) {
    return builder.add("props.getBoolean(name, $L)", info.mProperty.defaultBoolean());
  } if (propertyType.equals(TypeName.DOUBLE)) {
    double defaultDouble = info.mProperty.defaultDouble();
    if (Double.isNaN(defaultDouble)) {
      return builder.add("props.getDouble(name, $T.NaN)", Double.class);
    } else {
      return builder.add("props.getDouble(name, $Lf)", defaultDouble);
    }
  }
  if (propertyType.equals(TypeName.FLOAT)) {
    float defaultFloat = info.mProperty.defaultFloat();
    if (Float.isNaN(defaultFloat)) {
      return builder.add("props.getFloat(name, $T.NaN)", Float.class);
    } else {
      return builder.add("props.getFloat(name, $Lf)", defaultFloat);
    }
  }
  if (propertyType.equals(TypeName.INT)) {
    return builder.add("props.getInt(name, $L)", info.mProperty.defaultInt());
  }

  throw new IllegalArgumentException();
}
 
開發者ID:qq565999484,項目名稱:RNLearn_Project1,代碼行數:43,代碼來源:ReactPropertyProcessor.java

示例14: buildConstructorFnMethod

import com.squareup.javapoet.CodeBlock; //導入方法依賴的package包/類
@Nonnull
private static MethodSpec.Builder buildConstructorFnMethod( @Nonnull final ComponentDescriptor descriptor )
{
  final ParameterizedTypeName constructorType = getJsConstructorFnType( descriptor );

  final MethodSpec.Builder method =
    MethodSpec.methodBuilder( "getConstructorFunction" ).
      addAnnotation( NONNULL_CLASSNAME ).
      addModifiers( Modifier.STATIC, Modifier.PRIVATE ).
      returns( constructorType );

  method.addStatement( "final $T componentConstructor = $T::new",
                       constructorType,
                       ClassName.bestGuess( "NativeReactComponent" ) );
  final CodeBlock.Builder codeBlock = CodeBlock.builder();
  codeBlock.beginControlFlow( "if ( $T.enableComponentNames() )", REACT_CONFIG_CLASSNAME );
  codeBlock.addStatement( "$T.asPropertyMap( componentConstructor ).set( \"displayName\", $S )",
                          JS_CLASSNAME,
                          descriptor.getName() );
  codeBlock.endControlFlow();

  method.addCode( codeBlock.build() );

  final Map<String, TypeMirror> childContextTypeFields =
    descriptor.hasChildContextFields() ? descriptor.getChildContextTypeFields() : Collections.emptyMap();
  final Map<String, TypeMirror> contextTypeFields = descriptor.getContextTypeFields();
  if ( !childContextTypeFields.isEmpty() || !contextTypeFields.isEmpty() )
  {
    method.addStatement( "final $T valid = () -> null", REACT_PROP_TYPE_CLASSNAME );
  }
  if ( !contextTypeFields.isEmpty() )
  {
    method.addStatement( "final $T<$T> contextTypes = $T.of()",
                         JS_PROPERTY_MAP_CLASSNAME,
                         Object.class,
                         JS_PROPERTY_MAP_CLASSNAME );
    for ( final String contextKey : contextTypeFields.keySet() )
    {
      method.addStatement( "contextTypes.set( $S, valid )", contextKey );
    }
    method.addStatement( "$T.asPropertyMap( componentConstructor ).set( \"contextTypes\", contextTypes )",
                         JS_CLASSNAME );
  }
  if ( !childContextTypeFields.isEmpty() )
  {
    method.addStatement( "final $T<$T> childContextTypes = $T.of()",
                         JS_PROPERTY_MAP_CLASSNAME,
                         Object.class,
                         JS_PROPERTY_MAP_CLASSNAME );
    for ( final String childContextKey : childContextTypeFields.keySet() )
    {
      method.addStatement( "childContextTypes.set( $S, valid )", childContextKey );
    }
    method.addStatement( "$T.asPropertyMap( componentConstructor ).set( \"childContextTypes\", childContextTypes )",
                         JS_CLASSNAME );
  }
  if ( descriptor.hasDefaultPropsMethod() )
  {
    method.addStatement( "$T.asPropertyMap( componentConstructor ).set( \"defaultProps\", $T.$N() )",
                         JS_CLASSNAME,
                         descriptor.getClassName(),
                         descriptor.getDefaultPropsMethod().getSimpleName().toString() );
  }
  method.addStatement( "return componentConstructor" );
  return method;
}
 
開發者ID:react4j,項目名稱:react4j,代碼行數:67,代碼來源:Generator.java

示例15: writeValue

import com.squareup.javapoet.CodeBlock; //導入方法依賴的package包/類
public static CodeBlock writeValue(Types types, JsonProperty property, FieldSpec json) {
  //TODO If write method declares JSONException then don't wrap all puts.
  //TODO Handle collections.
  TypeName type = getTypeNameFromProperty(property, types);
  CodeBlock.Builder builder = CodeBlock.builder();

  if (type.equals(STRING)) {
    builder.addStatement("$N.put($S, $N())", json, property.serializedName(),
        property.methodName);
  } else if (type.equals(TypeName.INT) || type.equals(TypeName.INT.box())) {
    builder.addStatement("$N.put($S, $N())", json, property.serializedName(),
        property.methodName);
  } else if (type.equals(TypeName.DOUBLE) || type.equals(TypeName.DOUBLE.box())) {
    builder.addStatement("$N.put($S, $N())", json, property.serializedName(),
        property.methodName);
  } else if (type.equals(TypeName.FLOAT) || type.equals(TypeName.FLOAT.box())) {
    builder.addStatement("$N.put($S, $N())", json, property.serializedName(),
        property.methodName);
  } else if (type.equals(TypeName.BOOLEAN) || type.equals(TypeName.BOOLEAN.box())) {
    builder.addStatement("$N.put($S, $N())", json, property.serializedName(),
        property.methodName);
  } else if (type.equals(TypeName.LONG) || type.equals(TypeName.LONG.box())) {
    builder.addStatement("$N.put($S, $N())", json, property.serializedName(),
        property.methodName);
  } else if (type.equals(TypeName.SHORT) || type.equals(TypeName.SHORT.box())) {
    builder.addStatement("$N.put($S, $N())", json, property.serializedName(),
        property.methodName);
  } else if (type.equals(TypeName.BYTE) || type.equals(TypeName.BYTE.box())) {
    builder.addStatement("$N.put($S, $N())", json, property.serializedName(),
        property.methodName);
  } else if (type.equals(TypeName.CHAR) || type.equals(TypeName.CHAR.box())) {
    builder.addStatement("$N.put($S, String.valueOf($N()))", json, property.serializedName(),
        property.methodName);
  } else if (type.equals(ENUM)) {
    builder.addStatement("$N.put($S, $N().name())", json, property.serializedName(),
        property.methodName);
  } else {
    throw new IllegalStateException(String.format("supportedType [%s] with no method.", type));
  }

  return builder.build();
}
 
開發者ID:setheclark,項目名稱:auto-value-json,代碼行數:43,代碼來源:JsonGeneratorUtils.java


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