Java 类com.squareup.javapoet.MethodSpec.Builder 实例源码

项目:GitHub    文件:StringFieldType.java   
@Override
public void serialize(Builder builder, int depth, String fieldName, List<String> processedFieldNames, String getter, boolean isObjectProperty, boolean checkIfNull, boolean writeIfNull, boolean writeCollectionElementIfNull) {
    if (checkIfNull) {
        builder.beginControlFlow("if ($L != null)", getter);
    }

    if (isObjectProperty) {
        builder.addStatement("$L.writeStringField($S, $L)", JSON_GENERATOR_VARIABLE_NAME, fieldName, getter);
    } else {
        builder.addStatement("$L.writeString($L)", JSON_GENERATOR_VARIABLE_NAME, getter);
    }

    if (checkIfNull) {
        if (writeIfNull) {
            builder.nextControlFlow("else");

            if (isObjectProperty) {
                builder.addStatement("$L.writeFieldName($S)", JSON_GENERATOR_VARIABLE_NAME, fieldName);
            }
            builder.addStatement("$L.writeNull()", JSON_GENERATOR_VARIABLE_NAME);
        }

        builder.endControlFlow();
    }
}
项目:GitHub    文件:ParameterizedTypeField.java   
@Override
public void serialize(Builder builder, int depth, String fieldName, List<String> processedFieldNames, String getter, boolean isObjectProperty, boolean checkIfNull, boolean writeIfNull, boolean writeCollectionElementIfNull) {
    if (checkIfNull) {
        builder.beginControlFlow("if ($L != null)", getter);
    }

    if (isObjectProperty) {
        builder.addStatement("$L.writeFieldName($S)", JSON_GENERATOR_VARIABLE_NAME, fieldName);
    }
    builder.addStatement("$L.serialize($L, $L, true)", mJsonMapperVariableName, getter, JSON_GENERATOR_VARIABLE_NAME);

    if (checkIfNull) {
        if (writeIfNull) {
            builder.nextControlFlow("else");

            if (isObjectProperty) {
                builder.addStatement("$L.writeFieldName($S)", JSON_GENERATOR_VARIABLE_NAME, fieldName);
            }
            builder.addStatement("$L.writeNull()", JSON_GENERATOR_VARIABLE_NAME);
        }
        builder.endControlFlow();
    }
}
项目:GitHub    文件:BooleanFieldType.java   
@Override
public void serialize(Builder builder, int depth, String fieldName, List<String> processedFieldNames, String getter, boolean isObjectProperty, boolean checkIfNull, boolean writeIfNull, boolean writeCollectionElementIfNull) {
    if (!isPrimitive && checkIfNull) {
        builder.beginControlFlow("if ($L != null)", getter);
    }

    if (isObjectProperty) {
        builder.addStatement("$L.writeBooleanField($S, $L)", JSON_GENERATOR_VARIABLE_NAME, fieldName, getter);
    } else {
        builder.addStatement("$L.writeBoolean($L)", JSON_GENERATOR_VARIABLE_NAME, getter);
    }

    if (!isPrimitive && checkIfNull) {
        if (writeIfNull) {
            builder.nextControlFlow("else");

            if (isObjectProperty) {
                builder.addStatement("$L.writeFieldName($S)", JSON_GENERATOR_VARIABLE_NAME, fieldName);
            }
            builder.addStatement("$L.writeNull()", JSON_GENERATOR_VARIABLE_NAME);
        }

        builder.endControlFlow();
    }
}
项目:GitHub    文件:NumberFieldType.java   
@Override
public void serialize(Builder builder, int depth, String fieldName, List<String> processedFieldNames, String getter, boolean isObjectProperty, boolean checkIfNull, boolean writeIfNull, boolean writeCollectionElementIfNull) {
    if (!isPrimitive && checkIfNull) {
        builder.beginControlFlow("if ($L != null)", getter);
    }

    if (isObjectProperty) {
        builder.addStatement("$L.writeNumberField($S, $L)", JSON_GENERATOR_VARIABLE_NAME, fieldName, getter);
    } else {
        builder.addStatement("$L.writeNumber($L)", JSON_GENERATOR_VARIABLE_NAME, getter);
    }

    if (!isPrimitive && checkIfNull) {
        if (writeIfNull) {
            builder.nextControlFlow("else");

            if (isObjectProperty) {
                builder.addStatement("$L.writeFieldName($S)", JSON_GENERATOR_VARIABLE_NAME, fieldName);
            }
            builder.addStatement("$L.writeNull()", JSON_GENERATOR_VARIABLE_NAME);
        }

        builder.endControlFlow();
    }
}
项目:GitHub    文件:JsonFieldType.java   
@Override
public void serialize(Builder builder, int depth, String fieldName, List<String> processedFieldNames, String getter, boolean isObjectProperty, boolean checkIfNull, boolean writeIfNull, boolean writeCollectionElementIfNull) {

    if (checkIfNull) {
        builder.beginControlFlow("if ($L != null)", getter);
    }

    if (isObjectProperty) {
        builder.addStatement("$L.writeFieldName($S)", JSON_GENERATOR_VARIABLE_NAME, fieldName);
    }

    builder.addStatement("$L.serialize($L, $L, true)", mMapperVariableName, getter, JSON_GENERATOR_VARIABLE_NAME);

    if (checkIfNull) {
        if (writeIfNull) {
            builder.nextControlFlow("else");

            if (isObjectProperty) {
                builder.addStatement("$L.writeFieldName($S)", JSON_GENERATOR_VARIABLE_NAME, fieldName);
            }
            builder.addStatement("$L.writeNull()", JSON_GENERATOR_VARIABLE_NAME);
        }

        builder.endControlFlow();
    }
}
项目:GitHub    文件:DynamicFieldType.java   
@Override
public void serialize(Builder builder, int depth, String fieldName, List<String> processedFieldNames, String getter, boolean isObjectProperty, boolean checkIfNull, boolean writeIfNull, boolean writeCollectionElementIfNull) {
    if (!mTypeName.isPrimitive() && checkIfNull) {
        builder.beginControlFlow("if ($L != null)", getter);
    }

    builder.addStatement("$T.typeConverterFor($T.class).serialize($L, $S, $L, $L)", LoganSquare.class, mTypeName, getter, isObjectProperty
            ? fieldName : null, isObjectProperty, JSON_GENERATOR_VARIABLE_NAME);

    if (!mTypeName.isPrimitive() && checkIfNull) {
        if (writeIfNull) {
            builder.nextControlFlow("else");

            if (isObjectProperty) {
                builder.addStatement("$L.writeFieldName($S)", JSON_GENERATOR_VARIABLE_NAME, fieldName);
            }
            builder.addStatement("$L.writeNull()", JSON_GENERATOR_VARIABLE_NAME);
        }
        builder.endControlFlow();
    }
}
项目:GitHub    文件:UnknownFieldType.java   
@Override
public void serialize(Builder builder, int depth, String fieldName, List<String> processedFieldNames, String getter, boolean isObjectProperty, boolean checkIfNull, boolean writeIfNull, boolean writeCollectionElementIfNull) {
    if (checkIfNull) {
        builder.beginControlFlow("if ($L != null)", getter);
    }

    builder.addStatement("$L.serialize($L, $L, $L)", ObjectMapperInjector.getMapperVariableName(ObjectMapper.class), getter, JSON_GENERATOR_VARIABLE_NAME, isObjectProperty);

    if (checkIfNull) {
        if (writeIfNull) {
            builder.nextControlFlow("else");

            if (isObjectProperty) {
                builder.addStatement("$L.writeFieldName($S)", JSON_GENERATOR_VARIABLE_NAME, fieldName);
            }
            builder.addStatement("$L.writeNull()", JSON_GENERATOR_VARIABLE_NAME);
        }

        builder.endControlFlow();
    }
}
项目:dataenum    文件:ValueTypeFactory.java   
private static MethodSpec createAsSpecMethod(OutputValue value, OutputSpec spec) {
  List<TypeVariableName> missingTypeVariables = extractMissingTypeVariablesForValue(value, spec);

  Builder builder =
      MethodSpec.methodBuilder("as" + spec.outputClass().simpleName())
          .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
          .returns(spec.parameterizedOutputClass())
          .addTypeVariables(missingTypeVariables)
          .addStatement("return ($T) this", spec.parameterizedOutputClass());

  // if there are type variables that this sub-type doesn't use, they will lead to 'unchecked
  // cast'
  // warnings when compiling the generated code. These warnings are safe to suppress, since this
  // sub type will never use those type variables.
  if (!missingTypeVariables.isEmpty()) {
    builder.addAnnotation(SUPPRESS_UNCHECKED_WARNINGS);
  }

  return builder.build();
}
项目:mnemonic    文件:AnnotatedDurableEntityClass.java   
protected void buildExtraMethodSpecs(TypeSpec.Builder typespecbuilder) throws AnnotationProcessingException {
  MethodInfo methodinfo;
  CodeBlock.Builder code;
  for (String name : m_extramtdinfo.keySet()) {
    methodinfo = m_extramtdinfo.get(name);
    code = CodeBlock.builder();
    switch (name) {
      case "getNativeFieldInfo_static":
        code.addStatement("return $1N", m_fieldsinfo.get("nfieldinfo").name);
        break;
      default:
        throw new AnnotationProcessingException(null, "Method %s is not supported.", name);
    }
    typespecbuilder.addMethod(methodinfo.specbuilder.addCode(code.build()).build());
  }
}
项目:SensorAnnotations    文件:SensorAnnotationsFileBuilder.java   
/**
 * Creates the implementation of {@code SensorEventListener#onSensorChanged(SensorEvent)} which
 * calls the annotated method on our target class.
 *
 * @param annotatedMethod Method annotated with {@code OnSensorChanged}.
 * @return {@link MethodSpec} of {@code SensorEventListener#onSensorChanged(SensorEvent)}.
 */
@NonNull
private static MethodSpec createOnSensorChangedListenerMethod(
    @Nullable AnnotatedMethod annotatedMethod) {
    ParameterSpec sensorEventParameter = ParameterSpec.builder(SENSOR_EVENT, "event").build();
    Builder methodBuilder =
        getBaseMethodBuilder("onSensorChanged").addParameter(sensorEventParameter);

    if (annotatedMethod != null) {
        ExecutableElement sensorChangedExecutableElement =
            annotatedMethod.getExecutableElement();
        methodBuilder.addStatement("target.$L($N)",
            sensorChangedExecutableElement.getSimpleName(), sensorEventParameter);
    }

    return methodBuilder.build();
}
项目:SensorAnnotations    文件:SensorAnnotationsFileBuilder.java   
/**
 * Creates the implementation of {@code SensorEventListener#onAccuracyChanged(Sensor, int)}
 * which calls the annotated method on our target class.
 *
 * @param annotatedMethod Method annotated with {@link OnAccuracyChanged}.
 * @return {@link MethodSpec} of {@code SensorEventListener#onAccuracyChanged(Sensor, int)}.
 */
@NonNull
private static MethodSpec createOnAccuracyChangedListenerMethod(
    @Nullable AnnotatedMethod annotatedMethod) {
    ParameterSpec sensorParameter = ParameterSpec.builder(SENSOR, "sensor").build();
    ParameterSpec accuracyParameter = ParameterSpec.builder(TypeName.INT, "accuracy").build();
    Builder methodBuilder =
        getBaseMethodBuilder("onAccuracyChanged").addParameter(sensorParameter)
            .addParameter(accuracyParameter);

    if (annotatedMethod != null) {
        ExecutableElement accuracyChangedExecutableElement =
            annotatedMethod.getExecutableElement();
        methodBuilder.addStatement("target.$L($N, $N)",
            accuracyChangedExecutableElement.getSimpleName(), sensorParameter,
            accuracyParameter);
    }

    return methodBuilder.build();
}
项目:bsoneer    文件:BsoneeCodecProviderGenerator.java   
public JavaFile getJavaFile() {
    ClassName bsoneerCodecProviderClassName = ClassName.get(basePackage, "BsoneeCodecProvider");

    TypeSpec.Builder codecProviderBuilder = TypeSpec.classBuilder(bsoneerCodecProviderClassName.simpleName())
            .addJavadoc(ProcessorJavadocs.GENERATED_BY_BSONEER)
            .addSuperinterface(CodeUtil.bsonCodecProviderTypeName())
            .addModifiers(PUBLIC).addAnnotation(AnnotationSpec.builder(Generated.class)
                    .addMember("value", "$S", BsonProcessor.class.getCanonicalName())
                    .build());;

    addBaseConstructor(codecProviderBuilder);
    addGetCodecMethod(codecProviderBuilder);

    return JavaFile.builder(bsoneerCodecProviderClassName.packageName(), codecProviderBuilder.build())
            .addFileComment(ProcessorJavadocs.GENERATED_BY_BSONEER)
            .indent("\t")
            .build();
}
项目:bsoneer    文件:BsoneeCodecProviderGenerator.java   
private void addGetCodecMethod(com.squareup.javapoet.TypeSpec.Builder codecProviderBuilder) {
    TypeVariableName typeVariableName = TypeVariableName.get("T");
    TypeName clazzName = ParameterizedTypeName.get(ClassName.get(Class.class), typeVariableName);
    TypeName codecName = ParameterizedTypeName.get((ClassName) CodeUtil.bsonCodecTypeName(), typeVariableName);

    Builder methodSpec = MethodSpec.methodBuilder("get")
            .addAnnotation(Override.class)
            .addAnnotation(Util.suppressWarningsAnnotation(true, false))
            .addModifiers(Modifier.PUBLIC)
            .addParameter(ParameterSpec.builder(clazzName, "clazz", Modifier.FINAL).build())
            .addParameter(CodeUtil.bsonRegistryParameter())
            .addTypeVariable(typeVariableName)
            .returns(codecName)
            .addJavadoc("{@inhericDoc}\n");

    for (ClassName entityClassName : generated) {
        ClassName bsoneerCodecClassName = Util.bsoneeName(entityClassName, GeneratedClasses.BSONEE_CODEC_SUFFIX);
        methodSpec.beginControlFlow("if (clazz == $T.class)", entityClassName);
        methodSpec.addStatement("return (Codec<T>) new $T(registry)", bsoneerCodecClassName);
        methodSpec.endControlFlow();
    }

    methodSpec.addStatement("return null");
    codecProviderBuilder.addMethod(methodSpec.build());
}
项目:bsoneer    文件:SetterGenerator.java   
public void writeBody(TypeSpec.Builder codecBuilder, ClassName entityClassName) {
    TypeName setterIface = ParameterizedTypeName.get(ClassName.get(BsoneeBaseSetter.class), entityClassName);
    Map<String, String> setters = new LinkedHashMap<String, String>();

    for (Property property : bean.getOwnAndInheritedProperties()) {
        String setterClassName = property.getUpperName() + "Setter";
        setters.put(property.getBsonNames().iterator().next(), setterClassName);
        codecBuilder.addType(createSetterClass(entityClassName, setterIface, setterClassName, property).build());
    }

    Builder setupSetterBuilder = MethodSpec.methodBuilder("setupSetters").addModifiers(Modifier.PROTECTED);
    for (Entry<String, String> entry : setters.entrySet()) {
        setupSetterBuilder.addStatement("settersByName.put(\"$L\",new $L())",
                entry.getKey(), entry.getValue());
    }
    codecBuilder.addMethod(setupSetterBuilder.build());
}
项目:bsoncodec-apt    文件:ConversionObjectIdCodeGen.java   
@Override
public void addDecodeStatements(CodeGeneratorContext ctx) {
    Builder builder = ctx.builder();
    IdModel idModel = ctx.field().idModel();

    builder.addStatement("$T id = reader.readObjectId()", ObjectId.class);

    if (idModel != null) {
        if (idModel.conversion() == IdConversion.HEX_OBJECTID) {
            builder.addStatement(ctx.setter("id.toHexString()"));
        }
        else if (idModel.conversion() == IdConversion.BASE64_OBJECTID) {
            builder.addStatement(
                    ctx.setter("$T.getUrlEncoder().encodeToString(id.toByteArray())"),
                    Base64.class);
        }
    }
}
项目:bsoncodec-apt    文件:ConversionUUIDCodeGen.java   
@Override
public void addDecodeStatements(CodeGeneratorContext ctx) {
    Builder builder = ctx.builder();
    IdModel idModel = ctx.field().idModel();

    builder.addStatement("$T id = this.uUIDCodec.decode(reader, decoderContext)",
            UUID.class);

    if (idModel != null) {
        if (idModel.conversion() == IdConversion.HEX_UUID) {
            builder.addStatement(ctx.setter("id.toString()"));
        }
        else if (idModel.conversion() == IdConversion.BASE64_UUID) {
            builder.addStatement("$T bb = $T.wrap(new byte[16])", ByteBuffer.class,
                    ByteBuffer.class);
            builder.addStatement("bb.putLong(id.getMostSignificantBits())");
            builder.addStatement("bb.putLong(id.getLeastSignificantBits())");
            builder.addStatement(
                    ctx.setter("$T.getUrlEncoder().encodeToString(bb.array())"),
                    Base64.class);
        }
    }
}
项目:GitHub    文件:BooleanFieldType.java   
@Override
public void parse(Builder builder, int depth, String setter, Object... setterFormatArgs) {
    if (isPrimitive) {
        setter = replaceLastLiteral(setter, "$L.getValueAsBoolean()");
        builder.addStatement(setter, expandStringArgs(setterFormatArgs, JSON_PARSER_VARIABLE_NAME));
    } else {
        setter = replaceLastLiteral(setter, "$L.getCurrentToken() == $T.VALUE_NULL ? null : Boolean.valueOf($L.getValueAsBoolean())");
        builder.addStatement(setter, expandStringArgs(setterFormatArgs, JSON_PARSER_VARIABLE_NAME, JsonToken.class, JSON_PARSER_VARIABLE_NAME));
    }
}
项目:GitHub    文件:ByteFieldType.java   
@Override
public void parse(Builder builder, int depth, String setter, Object... setterFormatArgs) {
    if (isPrimitive) {
        setter = replaceLastLiteral(setter, "(byte)$L.getValueAsInt()");
        builder.addStatement(setter, expandStringArgs(setterFormatArgs, JSON_PARSER_VARIABLE_NAME));
    } else {
        setter = replaceLastLiteral(setter, "$L.getCurrentToken() == $T.VALUE_NULL ? null : Byte.valueOf((byte)$L.getValueAsInt())");
        builder.addStatement(setter, expandStringArgs(setterFormatArgs, JSON_PARSER_VARIABLE_NAME, JsonToken.class, JSON_PARSER_VARIABLE_NAME));
    }
}
项目:GitHub    文件:DoubleFieldType.java   
@Override
public void parse(Builder builder, int depth, String setter, Object... setterFormatArgs) {
    if (isPrimitive) {
        setter = replaceLastLiteral(setter, "$L.getValueAsDouble()");
        builder.addStatement(setter, expandStringArgs(setterFormatArgs, JSON_PARSER_VARIABLE_NAME));
    } else {
        setter = replaceLastLiteral(setter, "$L.getCurrentToken() == $T.VALUE_NULL ? null : Double.valueOf($L.getValueAsDouble())");
        builder.addStatement(setter, expandStringArgs(setterFormatArgs, JSON_PARSER_VARIABLE_NAME, JsonToken.class, JSON_PARSER_VARIABLE_NAME));
    }
}
项目:GitHub    文件:LongFieldType.java   
@Override
public void parse(Builder builder, int depth, String setter, Object... setterFormatArgs) {
    if (isPrimitive) {
        setter = replaceLastLiteral(setter, "$L.getValueAsLong()");
        builder.addStatement(setter, expandStringArgs(setterFormatArgs, JSON_PARSER_VARIABLE_NAME));
    } else {
        setter = replaceLastLiteral(setter, "$L.getCurrentToken() == $T.VALUE_NULL ? null : Long.valueOf($L.getValueAsLong())");
        builder.addStatement(setter, expandStringArgs(setterFormatArgs, JSON_PARSER_VARIABLE_NAME, JsonToken.class, JSON_PARSER_VARIABLE_NAME));
    }
}
项目:GitHub    文件:FloatFieldType.java   
@Override
public void parse(Builder builder, int depth, String setter, Object... setterFormatArgs) {
    if (isPrimitive) {
        setter = replaceLastLiteral(setter, "(float)$L.getValueAsDouble()");
        builder.addStatement(setter, expandStringArgs(setterFormatArgs, JSON_PARSER_VARIABLE_NAME));
    } else {
        setter = replaceLastLiteral(setter, "$L.getCurrentToken() == $T.VALUE_NULL ? null : new Float($L.getValueAsDouble())");
        builder.addStatement(setter, expandStringArgs(setterFormatArgs, JSON_PARSER_VARIABLE_NAME, JsonToken.class, JSON_PARSER_VARIABLE_NAME));
    }
}
项目:GitHub    文件:IntegerFieldType.java   
@Override
public void parse(Builder builder, int depth, String setter, Object... setterFormatArgs) {
    if (isPrimitive) {
        setter = replaceLastLiteral(setter, "$L.getValueAsInt()");
        builder.addStatement(setter, expandStringArgs(setterFormatArgs, JSON_PARSER_VARIABLE_NAME));
    } else {
        setter = replaceLastLiteral(setter, "$L.getCurrentToken() == $T.VALUE_NULL ? null : Integer.valueOf($L.getValueAsInt())");
        builder.addStatement(setter, expandStringArgs(setterFormatArgs, JSON_PARSER_VARIABLE_NAME, JsonToken.class, JSON_PARSER_VARIABLE_NAME));
    }
}
项目:GitHub    文件:MapCollectionType.java   
@Override
public void parse(Builder builder, int depth, String setter, Object... setterFormatArgs) {
    Type parameterType = parameterTypes.get(1);

    final String mapVariableName = "map" + depth;
    final String keyVariableName = "key" + depth;

    final String instanceCreator = String.format("$T<$T, %s> $L = new $T<$T, %s>()", parameterType.getParameterizedTypeString(), parameterType.getParameterizedTypeString());
    final Object[] instanceCreatorArgs = expandStringArgs(getTypeName(), String.class, parameterType.getParameterizedTypeStringArgs(), mapVariableName, getTypeName(), String.class, parameterType.getParameterizedTypeStringArgs());

    builder.beginControlFlow("if ($L.getCurrentToken() == $T.START_OBJECT)", JSON_PARSER_VARIABLE_NAME, JsonToken.class)
            .addStatement(instanceCreator, instanceCreatorArgs)
            .beginControlFlow("while ($L.nextToken() != $T.END_OBJECT)", JSON_PARSER_VARIABLE_NAME, JsonToken.class)
            .addStatement("$T $L = $L.getText()", String.class, keyVariableName, JSON_PARSER_VARIABLE_NAME)
            .addStatement("$L.nextToken()", JSON_PARSER_VARIABLE_NAME)
            .beginControlFlow("if ($L.getCurrentToken() == $T.VALUE_NULL)", JSON_PARSER_VARIABLE_NAME, JsonToken.class)
            .addStatement("$L.put($L, null)", mapVariableName, keyVariableName)
            .nextControlFlow("else");

    parameterType.parse(builder, depth + 1, "$L.put($L, $L)", mapVariableName, keyVariableName);

    builder
            .endControlFlow()
            .endControlFlow()
            .addStatement(setter, expandStringArgs(setterFormatArgs, mapVariableName))
            .nextControlFlow("else")
            .addStatement(setter, expandStringArgs(setterFormatArgs, "null"))
            .endControlFlow();
}
项目:GitHub    文件:SingleParameterCollectionType.java   
@Override
public void parse(Builder builder, int depth, String setter, Object... setterFormatArgs) {
    Type parameterType = parameterTypes.get(0);

    final String collectionVarName = "collection" + depth;
    final String valueVarName = "value" + depth;

    final String instanceCreator = String.format("$T<%s> $L = new $T<%s>()", parameterType.getParameterizedTypeString(), parameterType.getParameterizedTypeString());
    final Object[] instanceCreatorArgs = expandStringArgs(getTypeName(), parameterType.getParameterizedTypeStringArgs(), collectionVarName, getTypeName(), parameterType.getParameterizedTypeStringArgs());

    builder.beginControlFlow("if ($L.getCurrentToken() == $T.START_ARRAY)", JSON_PARSER_VARIABLE_NAME, JsonToken.class)
            .addStatement(instanceCreator, instanceCreatorArgs)
            .beginControlFlow("while ($L.nextToken() != $T.END_ARRAY)", JSON_PARSER_VARIABLE_NAME, JsonToken.class)
            .addStatement("$T $L", parameterType.getTypeName(), valueVarName);

    parameterType.parse(builder, depth + 1, "$L = $L", valueVarName);

    builder
            .addStatement("$L.add($L)", collectionVarName, valueVarName)
            .endControlFlow();

    builder
            .addStatement(setter, expandStringArgs(setterFormatArgs, collectionVarName))
            .nextControlFlow("else")
            .addStatement(setter, expandStringArgs(setterFormatArgs, "null"))
            .endControlFlow();
}
项目:GitHub    文件:SingleParameterCollectionType.java   
@Override
public void serialize(MethodSpec.Builder builder, int depth, String fieldName, List<String> processedFieldNames, String getter, boolean isObjectProperty, boolean checkIfNull, boolean writeIfNull, boolean writeCollectionElementIfNull) {
    Type parameterType = parameterTypes.get(0);
    final String cleanFieldName = TextUtils.toUniqueFieldNameVariable(fieldName, processedFieldNames);
    final String collectionVariableName = "lslocal" + cleanFieldName;
    final String elementVarName = "element" + depth;

    final String instanceCreator = String.format("final $T<%s> $L = $L", parameterType.getParameterizedTypeString());
    final Object[] instanceCreatorArgs = expandStringArgs(getGenericClass(), parameterType.getParameterizedTypeStringArgs(), collectionVariableName, getter);

    final String forLine = String.format("for (%s $L : $L)", parameterType.getParameterizedTypeString());
    final Object[] forLineArgs = expandStringArgs(parameterType.getParameterizedTypeStringArgs(), elementVarName, collectionVariableName);

    builder
            .addStatement(instanceCreator, instanceCreatorArgs)
            .beginControlFlow("if ($L != null)", collectionVariableName);

    if (isObjectProperty) {
        builder.addStatement("$L.writeFieldName($S)", JSON_GENERATOR_VARIABLE_NAME, fieldName);
    }

    builder
            .addStatement("$L.writeStartArray()", JSON_GENERATOR_VARIABLE_NAME)
            .beginControlFlow(forLine, forLineArgs)
            .beginControlFlow("if ($L != null)", elementVarName);

    parameterType.serialize(builder, depth + 1, collectionVariableName + "Element", processedFieldNames, elementVarName, false, false, false, writeCollectionElementIfNull);

    if (writeCollectionElementIfNull) {
        builder
                .nextControlFlow("else")
                .addStatement("$L.writeNull()", JSON_GENERATOR_VARIABLE_NAME);
    }

        builder
            .endControlFlow()
            .endControlFlow()
            .addStatement("$L.writeEndArray()", JSON_GENERATOR_VARIABLE_NAME)
            .endControlFlow();
}
项目:dataenum    文件:ValueTypeFactory.java   
public static TypeSpec create(
    OutputValue value, OutputSpec spec, MatchMethods matchMethods, MapMethods mapMethods)
    throws ParserException {

  TypeSpec.Builder typeBuilder =
      TypeSpec.classBuilder(value.outputClass())
          .addTypeVariables(value.typeVariables())
          .superclass(getSuperclassForValue(value, spec))
          .addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL);

  typeBuilder.addMethod(createConstructor(value));
  typeBuilder.addFields(createFields(value));
  typeBuilder.addMethods(createGetters(value));
  typeBuilder.addMethod(createEquals(value));

  typeBuilder.addMethod(createHashCode(value));

  typeBuilder.addMethod(createToString(value));
  typeBuilder.addMethod(matchMethods.createFoldVoidMethod(value));
  typeBuilder.addMethod(mapMethods.createFoldMethod(value));

  if (spec.hasTypeVariables()) {
    typeBuilder.addMethod(createAsSpecMethod(value, spec));
  }

  return typeBuilder.build();
}
项目:dataenum    文件:ValueTypeFactory.java   
private static MethodSpec createConstructor(OutputValue value) {
  MethodSpec.Builder constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE);
  for (Parameter parameter : value.parameters()) {
    constructor.addParameter(parameter.type(), parameter.name());

    if (parameter.type().isPrimitive() || parameter.canBeNull()) {
      constructor.addStatement("this.$1L = $1L", parameter.name());
    } else {
      constructor.addStatement("this.$1L = checkNotNull($1L)", parameter.name());
    }
  }
  return constructor.build();
}
项目:dataenum    文件:ValueTypeFactory.java   
private static MethodSpec createGetter(Parameter parameter) {
  MethodSpec.Builder builder =
      MethodSpec.methodBuilder(parameter.name())
          .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
          .returns(parameter.type())
          .addStatement("return $L", parameter.name());

  if (parameter.canBeNull()) {
    builder.addAnnotation(Nullable.class);
  } else if (!parameter.type().isPrimitive()) {
    builder.addAnnotation(Nonnull.class);
  }

  return builder.build();
}
项目:dataenum    文件:ValueTypeFactory.java   
private static MethodSpec createHashCode(OutputValue value) {
  MethodSpec.Builder result =
      MethodSpec.methodBuilder("hashCode")
          .addAnnotation(Override.class)
          .addModifiers(Modifier.PUBLIC)
          .returns(int.class);

  if (!value.hasParameters()) {
    result.addStatement("return 0");
    return result.build();
  }

  result.addStatement("int result = 0");
  for (Parameter parameter : value.parameters()) {
    String fieldName = parameter.name();
    result.addCode("result = result * 31 + ");
    if (parameter.type().isPrimitive()) {
      TypeName boxedType = parameter.type().box();
      result.addStatement("$T.valueOf($L).hashCode()", boxedType, fieldName);
    } else {
      if (parameter.canBeNull()) {
        result.addStatement("($1L != null ? $1L.hashCode() : 0)", fieldName);
      } else {
        result.addStatement("$L.hashCode()", fieldName);
      }
    }
  }
  result.addStatement("return result");
  return result.build();
}
项目:dataenum    文件:ValueTypeFactory.java   
private static MethodSpec createToString(OutputValue value) {
  MethodSpec.Builder result =
      MethodSpec.methodBuilder("toString")
          .addAnnotation(Override.class)
          .addModifiers(Modifier.PUBLIC)
          .returns(String.class);

  if (!value.parameters().iterator().hasNext()) {
    result.addStatement("return \"$L{}\"", value.name());
    return result.build();
  }

  result.addStatement("$1T builder = new $1T()", StringBuilder.class);

  boolean first = true;
  for (Parameter parameter : value.parameters()) {
    String fieldName = parameter.name();

    if (first) {
      first = false;
      result.addStatement("builder.append(\"$2L{$1N=\").append($1L)", fieldName, value.name());
    } else {
      result.addStatement("builder.append(\", $1N=\").append($1L)", fieldName);
    }
  }

  result.addStatement("return builder.append('}').toString()", value.name());

  return result.build();
}
项目:dataenum    文件:ValueMethods.java   
public MethodSpec createAsMethod(OutputSpec spec) {
  Builder builder =
      MethodSpec.methodBuilder("as" + value.name())
          .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
          .returns(value.parameterizedOutputClass())
          .addStatement("return ($T) this", value.parameterizedOutputClass());

  if (!ValueTypeFactory.extractMissingTypeVariablesForValue(value, spec).isEmpty()
      && value.hasTypeVariables()) {
    builder.addAnnotation(ValueTypeFactory.SUPPRESS_UNCHECKED_WARNINGS);
  }

  return builder.build();
}
项目:autojackson    文件:SimpleDeserializerCreator.java   
@Override
protected MethodSpec implementDeserializeMethod(TypeElement typeElement, Builder deserializeMethodBuilder) {
    Name className = typeElement.getSimpleName();

    return deserializeMethodBuilder.addStatement("$T codec = $L.getCodec()", ObjectCodec.class, JSON_PARSER_PARAMETER_NAME)
            .addStatement("$T rootNode = codec.readTree($L)", JsonNode.class, JSON_PARSER_PARAMETER_NAME)
            .addStatement("return codec.treeToValue(rootNode, $L$L.class)", className, ImplementationCreator.CLASS_IMPLEMENTATION_NAME_SUFFIX)
            .build();
}
项目:autojackson    文件:ComplexDeserializerCreator.java   
@Override
protected MethodSpec implementDeserializeMethod(TypeElement typeElement, Builder deserializeMethodBuilder) {
    Optional<DeserializationConstructs> constructs = loadConstructs(typeElement);
    if (!constructs.isPresent()) {
        return deserializeMethodBuilder.addStatement("return null").build();
    }

    TypeElement enumTypeElement = constructs.get().getEnumTypeElement();
    ImmutableList<Element> enumValueElements = constructs.get().getEnumValueElements();
    ExecutableElement enumValueAccessorMethod = constructs.get().getEnumValueAccessorMethod();
    ExecutableElement enumInstanceAccessorMethod = constructs.get().getEnumInstanceAccessorMethod();

    String memberVariableName = this.processorUtil.createMemberVariableName(enumValueAccessorMethod);

    deserializeMethodBuilder.addStatement("$T codec = $L.getCodec()", ObjectCodec.class, JSON_PARSER_PARAMETER_NAME)
            .addStatement("$T rootNode = codec.readTree($L)", JsonNode.class, JSON_PARSER_PARAMETER_NAME)
            .addStatement("$T typeNode = rootNode.get($S)", JsonNode.class, memberVariableName)
            .beginControlFlow("if (typeNode == null)")
            .addStatement("$T javaType = $L.constructType($T.class)", JavaType.class, DESERIALIZATION_CONTEXT_PARAMETER_NAME, enumTypeElement)
            .addStatement("throw new $T($L, \"$L not present\", javaType, null)", InvalidTypeIdException.class, JSON_PARSER_PARAMETER_NAME, memberVariableName)
            .endControlFlow()
            .addStatement("$T type = codec.treeToValue(typeNode, $T.$L)", enumTypeElement, enumTypeElement, "class")
            .beginControlFlow("switch (type)");

    enumValueElements.forEach(enumValueElement -> deserializeMethodBuilder
            .beginControlFlow("case $L:", enumValueElement)
            .addStatement("return codec.treeToValue(rootNode, $T.$L.$L)", enumTypeElement, enumValueElement, enumInstanceAccessorMethod)
            .endControlFlow());

    return deserializeMethodBuilder.beginControlFlow("default :")
            .addStatement("return null")
            .endControlFlow()
            .endControlFlow()
            .build();
}
项目:Mnemonic    文件:AnnotatedNonVolatileEntityClass.java   
protected void buildFieldSpecs(TypeSpec.Builder typespecbuilder, Map<String, FieldInfo> fieldinfos) {
FieldInfo fieldinfo;
for (String name : fieldinfos.keySet()) {
    fieldinfo = fieldinfos.get(name);
    if (null != fieldinfo.specbuilder) {
    typespecbuilder.addField(fieldinfo.specbuilder.build());
    }
}
   }
项目:mnemonic    文件:AnnotatedDurableEntityClass.java   
protected void buildFieldSpecs(TypeSpec.Builder typespecbuilder, Map<String, FieldInfo> fieldinfos) {
  FieldInfo fieldinfo;
  for (String name : fieldinfos.keySet()) {
    fieldinfo = fieldinfos.get(name);
    if (null != fieldinfo.specbuilder) {
      typespecbuilder.addField(fieldinfo.specbuilder.build());
    }
  }
}
项目:SensorAnnotations    文件:SensorAnnotationsFileBuilder.java   
/**
 * Return a {@link Builder} with the given method name and default properties.
 *
 * @param name The name of the method.
 * @return A base {@link Builder} to use for methods.
 */
@NonNull
private static Builder getBaseMethodBuilder(@NonNull String name) {
    return MethodSpec.methodBuilder(name)
        .addModifiers(Modifier.PUBLIC)
        .returns(void.class)
        .addAnnotation(Override.class);
}
项目:trinity    文件:ReadCursorMethodCreator.java   
@NotNull
@Override
public MethodSpec create() {
  Collection<ColumnMethod> setters = mColumnMethodRepository.findSettersForTableClass(mTableClass.getFullyQualifiedName());

  ClassName entityClassName = ClassName.get(mTableClass.getPackageName(), mTableClass.getClassName());

  Builder methodBuilder =
      MethodSpec.methodBuilder("read")
          .addModifiers(PUBLIC)
          .addParameter(CURSOR, "cursor", FINAL)
          .returns(entityClassName)
          .addStatement(
              "$T result = new $T()",
              entityClassName,
              entityClassName
          )
          .addCode("\n");

  ReadCursorCreatorFactory creatorFactory = new ReadCursorCreatorFactory("result", "cursor", mSerializerClassRepository);
  for (ColumnMethod setter : setters) {
    ReadCursorCreator readCursorCreator = creatorFactory.createReadCursorCreator(setter);
    methodBuilder.addCode(readCursorCreator.create());
  }

  return methodBuilder.addCode("\n")
      .addStatement("return result")
      .build();
}
项目:trinity    文件:CreateMethodCreator.java   
@NotNull
@Override
public MethodSpec create() {
  Parameter parameter = mMethod.getParameter();

  Builder builder = MethodSpec.methodBuilder(mMethod.getMethodName())
      .addJavadoc(createJavadoc())
      .addAnnotation(Override.class)
      .addModifiers(PUBLIC)
      .addParameter(ClassName.bestGuess(parameter.getFullyQualifiedType()), parameter.getVariableName(), FINAL)
      .returns(Long.class)
      .addStatement("$T result = null", Long.class)
      .addCode("\n")
      .addStatement("$T contentValues = $N($L)", CONTENT_VALUES, mCreateContentValuesSpec, parameter.getVariableName())
      .addStatement("$T id = mDatabase.insert($S, null, contentValues)", long.class, mTableClass.getTableName())
      .beginControlFlow("if (id != -1)");

  if (mPrimaryKeySetter != null && Long.class.getName().equals(mPrimaryKeySetter.getType())) {
    builder.addStatement("$L.$L(id)", parameter.getVariableName(), mPrimaryKeySetter.getMethodName());
  }

  builder.addStatement("result = id")
      .endControlFlow()
      .addCode("\n")
      .addStatement("return result");

  return builder.build();
}
项目:trinity    文件:CreateAllMethodCreator.java   
@NotNull
@Override
public MethodSpec create() {
  ClassName entityClassName = ClassName.get(mTableClass.getPackageName(), mTableClass.getClassName());
  Parameter parameter = mMethod.getParameter();
  if (parameter == null) {
    throw new IllegalStateException("Missing parameter.");
  }

  Builder builder = MethodSpec.methodBuilder(mMethod.getMethodName())
      .addJavadoc(createJavadoc())
      .addAnnotation(Override.class)
      .addModifiers(PUBLIC)
      .addParameter(TypeName.get(parameter.getType()), parameter.getVariableName(), FINAL)
      .beginControlFlow("try")
      .addStatement("$N.beginTransaction()", mDatabaseFieldSpec)
      .addCode("\n")
      .beginControlFlow("for ($T entity: $L)", entityClassName, parameter.getVariableName())
      .addStatement("$T contentValues = $N(entity)", CONTENT_VALUES, mCreateContentValuesSpec)
      .addStatement("$N.insert($S, null, contentValues)", mDatabaseFieldSpec, mTableClass.getTableName())
      .endControlFlow()
      .addCode("\n")
      .addStatement("$N.setTransactionSuccessful()", mDatabaseFieldSpec)
      .nextControlFlow("finally")
      .addStatement("$N.endTransaction()", mDatabaseFieldSpec)
      .endControlFlow();

  return builder.build();
}
项目:bsoneer    文件:GetterGenerator.java   
public void writeBody(Builder p) {
    for (Property property : bean.getOwnAndInheritedProperties()) {
        TypeMirror key = property.getResolvedType();

        String accessName = property.getGetterCall();
        boolean isPrimitive = key.getKind().isPrimitive();

        for (String bsonName : property.getBsonNames()) {
            com.squareup.javapoet.CodeBlock.Builder codeBuilder = CodeBlock
                    .builder();
            codeBuilder.addStatement("writer.writeName(\"$L\")", bsonName);

            for(EncodeCodeProvider scp:codeProviders){
                if ( scp.applies(property) ){
                    scp.putEncodeCode(codeBuilder, property.getResolvedType(), codeProviders, "value." + property.getGetterCall());
                    break;
                }
            }

            CodeBlock codeBlock = codeBuilder.build();
            if ("_id".equals(bsonName)) {
                codeBlock = writeAsId(codeBlock, false);
            }
            if (isPrimitive) {
                p.addCode(codeBlock);
            } else {
                writeCheckingForNull(p, accessName, codeBlock);
            }
        }
    }
}