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

项目:javabard    文件:ValueClassSpec.java   
public TypeSpec.Builder build() {
    TypeSpec.Builder tsb = TypeSpec.classBuilder(name);
    for (Map.Entry<String, Class<?>> entry : nameTypeMap.entrySet()) {
        FieldSpec field = FieldSpec.builder(
                ClassName.get(entry.getValue()), entry.getKey(), Modifier.PRIVATE)
                .build();
        tsb.addField(field);
    }
    if (getter) {
        tsb = GetterSpec.forType(tsb).build();
    }
    if (setter) {
        tsb = SetterSpec.forType(tsb).build();
    }
    if (builder) {
        tsb = BuilderSpec.forType(packageName, tsb).build();
    }
    return tsb;
}
项目:GitHub    文件:ObjectMapperInjector.java   
private void addUsedTypeConverterMethods(TypeSpec.Builder builder) {
    Set<TypeName> usedTypeConverters = new HashSet<>();

    for (JsonFieldHolder holder : mJsonObjectHolder.fieldMap.values()) {
        usedTypeConverters.addAll(holder.type.getUsedTypeConverters());
    }

    for (TypeName usedTypeConverter : usedTypeConverters) {
        final String variableName = getTypeConverterVariableName(usedTypeConverter);
        builder.addField(FieldSpec.builder(ParameterizedTypeName.get(ClassName.get(TypeConverter.class), usedTypeConverter), variableName)
                .addModifiers(Modifier.PRIVATE, Modifier.STATIC)
                .build()
        );

        builder.addMethod(MethodSpec.methodBuilder(getTypeConverterGetter(usedTypeConverter))
                .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
                .returns(ParameterizedTypeName.get(ClassName.get(TypeConverter.class), usedTypeConverter))
                .beginControlFlow("if ($L == null)", variableName)
                .addStatement("$L = $T.typeConverterFor($T.class)", variableName, LoganSquare.class, usedTypeConverter)
                .endControlFlow()
                .addStatement("return $L", variableName)
                .build()
        );
    }
}
项目:greycat    文件:ConstantGenerator.java   
private static JavaFile generateGlobalConstant(String packageName, Constant[] globalConstants) {
    TypeSpec.Builder javaClass = TypeSpec.classBuilder(CONSTANT_CLASS_NAME);
    javaClass.addModifiers(PUBLIC, FINAL);
    for (Constant constant : globalConstants) {
        String value = constant.value();
        if (constant.type().equals("Task") && value != null) {
            value = "greycat.Tasks.newTask().parse(\"" + value.replaceAll("\"", "'").trim() + "\",null);";
        } else if (constant.type().equals("String") && value != null) {
            value = "\""+value+"\"";
        }
        FieldSpec.Builder field = FieldSpec.builder(clazz(constant.type()), constant.name())
                .addModifiers(PUBLIC, STATIC);
        if (value != null) {
            field.addModifiers(FINAL).initializer(value);
        }
        javaClass.addField(field.build());
    }
    return JavaFile.builder(packageName, javaClass.build()).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();
}
项目:auto-value-json    文件:AutoValueJsonExtension.java   
private ImmutableMap<TypeMirror, FieldSpec> getTypeAdapters(List<JsonProperty> properties,
    NameAllocator nameAllocator) {
  Map<TypeMirror, FieldSpec> typeAdapters = new LinkedHashMap<>();
  for (JsonProperty property : properties) {
    if (property.typeAdapter != null && !typeAdapters.containsKey(property.typeAdapter)) {
      ClassName typeName = (ClassName) TypeName.get(property.typeAdapter);
      String name = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, typeName.simpleName());
      name = nameAllocator.newName(name, typeName);

      typeAdapters.put(property.typeAdapter,
          FieldSpec.builder(typeName, NameAllocator.toJavaIdentifier(name), PRIVATE, STATIC,
              FINAL).initializer("new $T()", typeName).build());
    }
  }

  return ImmutableMap.copyOf(typeAdapters);
}
项目:r-parser    文件:ExampleProcessor.java   
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
    parser.scan(roundEnvironment);
    TypeSpec.Builder builder = TypeSpec.classBuilder("Testing")
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL);
    for (Element element : roundEnvironment.getElementsAnnotatedWith(Parse.class))
        builder.addField(FieldSpec.builder(String.class, element.getSimpleName().toString())
                .addModifiers(Modifier.PRIVATE, Modifier.FINAL)
                .initializer("$S", parser.parse("com.example.rparser", element.getAnnotation(Parse.class).value()))
                .build());
    JavaFile javaFile = JavaFile.builder("com.example.rparser", builder.build())
            .build();
    try {
        javaFile.writeTo(filer);
    } catch (IOException ignored) {
    }
    return false;
}
项目:json2java4idea    文件:JacksonClassBuilder.java   
@Nonnull
@Override
protected List<FieldSpec> buildFields() {
    return getProperties().entrySet()
            .stream()
            .map(property -> {
                final String name = property.getKey();
                final TypeName type = property.getValue();

                final String fieldName = fieldNamePolicy.convert(name, type);
                return FieldSpec.builder(type, fieldName)
                        .addModifiers(Modifier.PRIVATE, Modifier.FINAL)
                        .build();
            })
            .collect(Collectors.toList());
}
项目:json2java4idea    文件:ModelClassBuilder.java   
@Nonnull
@Override
protected List<FieldSpec> buildFields() {
    return getProperties()
            .entrySet()
            .stream()
            .map(property -> {
                final String name = property.getKey();
                final TypeName type = property.getValue();
                final String fieldName = fieldNamePolicy.convert(name, type);
                return FieldSpec.builder(type, fieldName)
                        .addModifiers(Modifier.PRIVATE, Modifier.FINAL)
                        .build();
            })
            .collect(Collectors.toList());
}
项目:android-auto-mapper    文件:AutoMappperProcessor.java   
private ImmutableMap<TypeMirror, FieldSpec> getTypeAdapters(ImmutableList<Property> properties) {
    Map<TypeMirror, FieldSpec> typeAdapters = new LinkedHashMap<>();
    NameAllocator nameAllocator = new NameAllocator();
    nameAllocator.newName("CREATOR");
    for (Property property : properties) {
        if (property.typeAdapter != null && !typeAdapters.containsKey(property.typeAdapter)) {
            ClassName typeName = (ClassName) TypeName.get(property.typeAdapter);
            String name = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, typeName.simpleName());
            name = nameAllocator.newName(name, typeName);

            typeAdapters.put(property.typeAdapter, FieldSpec.builder(
                    typeName, NameAllocator.toJavaIdentifier(name), PRIVATE, STATIC, FINAL)
                    .initializer("new $T()", typeName).build());
        }
    }
    return ImmutableMap.copyOf(typeAdapters);
}
项目: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();
}
项目:Spyglass    文件:TestCallerGenerator.java   
private void checkCompiles(final TypeSpec anonymousTypeSpec) {
    // Anonymous class cannot be top level class, so nest the anonymous class as a field
    final TypeSpec wrapperTypeSpec = TypeSpec
            .classBuilder("Wrapper")
            .addField(FieldSpec.builder(ClassName.get(Data.class), "target").build())
            .addField(FieldSpec.builder(AndroidClassNames.CONTEXT, "context").build())
            .addField(FieldSpec.builder(AndroidClassNames.TYPED_ARRAY, "attrs").build())
            .addField(FieldSpec
                    .builder(TypeName.OBJECT, "o")
                    .initializer("$L", anonymousTypeSpec)
                    .build())
            .build();

    final JavaFile wrapperJavaFile = JavaFile
            .builder("", wrapperTypeSpec)
            .build();

    final Set<JavaFile> filesToCompile = new HashSet<>();

    filesToCompile.add(wrapperJavaFile);
    filesToCompile.add(CallerDef.SRC_FILE);

    CompileChecker.checkCompiles(filesToCompile);
}
项目:jso-builder    文件:JSOBuilderProcessor.java   
private TypeSpec createGlobalInterface() {
    return TypeSpec.classBuilder("Global")
            .addModifiers(Modifier.STATIC, Modifier.FINAL)
            .addAnnotation(AnnotationSpec.builder(ClassNames.JSINTEROP_JSTYPE)
                    .addMember("isNative", "true")
                    .addMember("namespace", "$T.GLOBAL", ClassNames.JSINTEROP_JSPACKAGE)
                    .build())
            .addFields(Stream.of(Object.class,
                    Boolean.TYPE, Byte.TYPE, Character.TYPE, Double.TYPE,
                    Float.TYPE, Integer.TYPE, Long.TYPE, Short.TYPE)
                    .map(type -> FieldSpec.builder(type, "UNDEFINED_" + type.getSimpleName().toUpperCase())
                            .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                            .addAnnotation(AnnotationSpec.builder(ClassNames.JSINTEROP_JSPROPERTY)
                                    .addMember("namespace", "$T.GLOBAL", ClassNames.JSINTEROP_JSPACKAGE)
                                    .addMember("name", "$S", "undefined")
                                    .build())
                            .build())
                .collect(Collectors.toList()))
            .build();
}
项目:D-Router    文件:RouterTableGenerator.java   
public void generateMappingTable(Filer filer) throws IOException {
    if (routerTable.isEmpty()) {
        return;
    }
    FieldSpec tableFieldSpec = FieldSpec.builder(Map.class, "routerTable")
            .addModifiers(Modifier.PRIVATE)
            .build();
    MethodSpec initTableMethodSpec = getInitTableMethodSpec();
    MethodSpec queryTableMethodSpec = getqueryTableMethodSpec();
    MethodSpec constructorMethodSpec = getconstructorMethodSpec(tableFieldSpec, initTableMethodSpec);
    MethodSpec addRouterMethodSpec = getAddRouterMethodSpec();
    TypeSpec routerTableClassTypeSpec = getRouterTableClassTypeSpec(tableFieldSpec, initTableMethodSpec, queryTableMethodSpec, constructorMethodSpec, addRouterMethodSpec);
    String packageName = Constants.GENERATED_PACKAGE_NAME;
    JavaFile javaFile = JavaFile.builder(packageName, routerTableClassTypeSpec).build();
    javaFile.writeTo(filer);
}
项目:android-auto-mapper    文件:Parcelables.java   
public static CodeBlock writeValueWithTypeAdapter(FieldSpec adapter, AutoMappperProcessor.Property p, ParameterSpec out) {
    CodeBlock.Builder block = CodeBlock.builder();

    if (p.isNullable()) {
        block.beginControlFlow("if ($N == null)", p.fieldName);
        block.addStatement("$N.writeInt(1)", out);
        block.nextControlFlow("else");
        block.addStatement("$N.writeInt(0)", out);
    }

    block.addStatement("$N.toParcel($N, $N)", adapter, p.fieldName, out);

    if (p.isNullable()) {
        block.endControlFlow();
    }

    return block.build();
}
项目:auto-adapter    文件:ViewHolderFactoryGenerator.java   
private void addFields(final TypeSpec.Builder classBuilder) {
    FieldSpec.Builder viewIdsField = FieldSpec.builder(int[].class, "viewIds", Modifier.PRIVATE, Modifier.STATIC,
            Modifier.FINAL);
    StringBuilder sb = new StringBuilder();
    sb.append("{");
    for (Integer id : viewIds) {
        sb.append(id).append(",");
    }

    if (viewIds.size() > 0) {
        sb.deleteCharAt(sb.length() - 1);
    }

    sb.append("}");
    viewIdsField.initializer(CodeBlock.of(sb.toString()));
    classBuilder.addField(viewIdsField.build());

}
项目:java-code-templates    文件:TemplateSubstitutionVisitor.java   
@Override
public DeferredTypeSpecBuilder visitVariableAsField(final VariableElement element, final DeferredTypeSpecBuilder builder) {
    final Modifier[] mods = modifiers(element);
    final ImmutableList<AnnotationSpec> annotations = copyableAnnotations(element);
    final boolean hasInit = Util.hasInitializer(element, trees);
    switch(SubstitutionKind.fromVariableElement(element)) {
    case SUBSTITUTABLE_FIELD:
        final boolean isConstant = isConstant(element);
        final boolean retainType = retainTypeFromTemplate(element);
        final TypeName elementType = applyTypeSubstitution(element.asType());
        final OutputTarget target = isConstant ? CONSTANTS : INSTANCE_FIELDS;
        descriptorInventory.beanProperties().forEach(prop -> {
            builder.wrapped().addField(FieldSpec
                    .builder(retainType ? elementType : descriptorInventory.applyTypeSubstitution(prop.typeName()),
                            isConstant ? prop.propertyName(UPPER_UNDERSCORE) : prop.propertyName(),
                            mods)
                    .addAnnotations(mergeAnnotations(descriptorInventory.annotations(prop, target), annotations))
                    .initializer(hasInit
                            ? descriptorInventory.fieldInitializer(prop, retainType ? elementType : rawType(prop.typeName()))
                                    : "")
                    .build());
        });
        break;

    default:
        builder.wrapped().addField(FieldSpec.builder(applyTypeSubstitution(element.asType()), simpleName(element), mods)
                .addAnnotations(annotations)
                .initializer(astSubstitutionProcessor.applySubstitutions(element))
                .build());
    }

    return builder;
}
项目:shoebill    文件:ShoebillProcessor.java   
private FieldSpec getSingletonField(ClassName className) {
    return FieldSpec
            .builder(className, "singleton")
            .addModifiers(Modifier.PRIVATE, Modifier.STATIC)
            .initializer("new $L()", className.simpleName())
            .build();
}
项目:shoebill    文件:ShoebillProcessor.java   
private MethodSpec getSingletonGetterMethod(ClassName className, FieldSpec singletonField) {
    return MethodSpec
            .methodBuilder("getInstance")
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
            .returns(className)
            .addStatement("return $N", singletonField)
            .build();
}
项目:GitHub    文件:FinalRClassBuilder.java   
private static void addResourceField(TypeSpec.Builder resourceType, VariableDeclarator variable,
    ClassName annotation) {
  String fieldName = variable.getId().getName();
  String fieldValue = variable.getInit().toString();
  FieldSpec.Builder fieldSpecBuilder = FieldSpec.builder(int.class, fieldName)
      .addModifiers(PUBLIC, STATIC, FINAL)
      .initializer(fieldValue);

  if (annotation != null) {
    fieldSpecBuilder.addAnnotation(annotation);
  }

  resourceType.addField(fieldSpecBuilder.build());
}
项目:raml-java-tools    文件:FieldSpecMatchers.java   
public static Matcher<FieldSpec> fieldName(Matcher<String> match) {

    return new FeatureMatcher<FieldSpec, String>(match, "field name", "field name") {

      @Override
      protected String featureValueOf(FieldSpec actual) {
        return actual.name;
      }
    };
  }
项目:raml-java-tools    文件:FieldSpecMatchers.java   
public static Matcher<FieldSpec> initializer(Matcher<String> match) {

    return new FeatureMatcher<FieldSpec, String>(match, "field initializer", "field initializer") {

      @Override
      protected String featureValueOf(FieldSpec actual) {
        return actual.initializer.toString();
      }
    };
  }
项目:jdoocsoup    文件:DataClassBuilderHandler.java   
private void parseDataFromDescriptor() {
    if (descriptor.getElementKind() == ElementKind.CLASS) {
        for (VariableElement var : descriptor.getFields()) {

            if (checkIfFieldForProcessing(var)) {
                continue;
            }

            DataClassBuilder.MethodDocs builderMethodDocsAnnotation = var.getAnnotation(DataClassBuilder.MethodDocs.class);
            DataClassBuilder.HasDefault hasDefaultAnnotation = var.getAnnotation(DataClassBuilder.HasDefault.class);

            FieldSpec.Builder fieldSpec = FieldSpec.builder(TypeName.get(var.asType()), var.getSimpleName().toString()).addModifiers(Modifier.PRIVATE);

            if (hasDefaultAnnotation != null) {
                fieldSpec.initializer(CodeBlock.of("$L", hasDefaultAnnotation.value()));
            }

            MethodSpec.Builder methodSpec = MethodSpec.methodBuilder(var.getSimpleName().toString()).addModifiers(Modifier.PUBLIC)
                    .addParameter(ParameterSpec.builder(TypeName.get(var.asType()), var.getSimpleName().toString()).build())
                    .addStatement("this.$N = $N", var.getSimpleName(), var.getSimpleName())
                    .addStatement("return this")
                    .returns(ClassName.get(descriptor.getPackageName(), descriptor.getDataClassBuilderName()));

            if (builderMethodDocsAnnotation != null) {
                methodSpec.addJavadoc(builderMethodDocsAnnotation.value() + "\n");
            }

            builderClassSpecBuilder.addField(fieldSpec.build());
            builderClassSpecBuilder.addMethod(methodSpec.build());
        }
    }

    builderClassSpecBuilder.addMethod(createBuilderMethodSpec());
    builderClassSpecBuilder.addMethod(createBuildMethodSpec());
    builderClassSpecBuilder.addMethod(createPrivateConstructor());
}
项目:raml-java-tools    文件:ObjectTypeHandlerPlugin.java   
@Override
public FieldSpec.Builder fieldBuilt(TypeDeclaration declaration, FieldSpec.Builder incoming, EventType eventType) {
    for (ObjectTypeHandlerPlugin plugin : plugins) {
        if ( incoming == null ) {
            break;
        }
        incoming = plugin.fieldBuilt(declaration, incoming, eventType);
    }

    return incoming;
}
项目:javabard    文件:GetterSpec.java   
/**
 *
 * @param field
 * @param namingConvention
 * @return
 */
public static MethodSpec.Builder forField(FieldSpec field, String namingConvention) {
    return MethodSpec.methodBuilder(makeName(namingConvention, field.name))
            .addJavadoc(field.javadoc)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .returns(field.type)
            .addStatement("return this.$N", field.name);
}
项目:autoproxy    文件:CommonClassGenerator.java   
/** {@inheritDoc} */
@Override
public boolean compose(@NonNull final Filer filer) {
    try {
        // compose class
        final FieldSpec[] members = createMembers();
        final TypeSpec.Builder classSpec = createClass(members);

        // constructor and predicate
        classSpec.addMethod(createConstructor().build());
        classSpec.addMethod(createPredicate().build());

        // auto-generate method proxy calls
        createMethods(classSpec);

        // if any after call annotation found in class/methods
        if (afterCalls.get()) {
            classSpec.addMethod(createAfterCall().build());
        }

        // save class to disk
        final JavaFile javaFile = JavaFile.builder(type.packageName.toString(), classSpec.build()).build();
        javaFile.writeTo(filer);

    } catch (final Throwable ignored) {
        ignored.printStackTrace(new PrintWriter(errors));
        return false;
    }

    return true;
}
项目:autoproxy    文件:CommonClassGenerator.java   
@NonNull
protected FieldSpec[] createMembers() {
    final List<FieldSpec> fields = new ArrayList<>();

    final TypeName typeOfField = TypeName.get(type.element.asType());
    final FieldSpec.Builder builder = FieldSpec.builder(typeOfField, "inner", Modifier.PROTECTED, Modifier.FINAL);
    fields.add(builder.build());

    return fields.toArray(new FieldSpec[0]);
}
项目:Surgeon    文件:SurgeonProcessor.java   
private Iterable<FieldSpec> buildRouterModuleFields() {
    ArrayList<FieldSpec> fieldSpecs = new ArrayList<>();
    FieldSpec f_mapping = FieldSpec.builder(HashMap.class, "mapping")
            .addModifiers(Modifier.PRIVATE, Modifier.FINAL)
            .build();
    fieldSpecs.add(f_mapping);
    return fieldSpecs;
}
项目:json-log-domain    文件:MarkerGenerator.java   
private static FieldSpec getField(ClassName name, Key key) {
    Class<?> type = parseTypeFormat(key.getType(), key.getFormat());

    if(type.isPrimitive()) {
        type = ClassUtils.primitiveToWrapper(type);
    }

    return FieldSpec.builder(type, key.getId(), Modifier.PRIVATE).build();
}
项目:json-log-domain    文件:TagGenerator.java   
private static MethodSpec getter(String methodName, FieldSpec field) {
    return MethodSpec.methodBuilder(methodName)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .returns(field.type)
            .addStatement("return $N", field)
            .build();
}
项目:react4j    文件:Generator.java   
private static FieldSpec.Builder buildProviderField( final @Nonnull ComponentDescriptor descriptor )
{
  return FieldSpec.builder( ParameterizedTypeName.get( PROVIDER_CLASSNAME,
                                                       TypeName.get( descriptor.getDeclaredType() ) ),
                            "c_provider",
                            Modifier.STATIC,
                            Modifier.PRIVATE );
}
项目:react4j    文件:Generator.java   
@Nonnull
private static FieldSpec.Builder buildEventHandlerField( @Nonnull final EventHandlerDescriptor eventHandler )
{
  final TypeName handlerType = TypeName.get( eventHandler.getEventHandlerType().asType() );
  final String handlerName = "_" + eventHandler.getMethod().getSimpleName().toString();
  return FieldSpec.builder( handlerType, handlerName, Modifier.FINAL, Modifier.PRIVATE ).
    addAnnotation( NONNULL_CLASSNAME ).
    initializer( "create$N()", handlerName );
}
项目:auto-value-json    文件:JsonGeneratorUtils.java   
static CodeBlock readValue(Types types, JsonProperty property, ParameterSpec json,
    FieldSpec field, FieldSpec key, NameAllocator nameAllocator) {
  //TODO Handle collections.
  TypeName type = getTypeNameFromProperty(property, types);
  CodeBlock.Builder builder = CodeBlock.builder();

  if (type.equals(STRING)) {
    builder.addStatement("$N = $N.getString($N)", field, json, key);
  } else if (type.equals(TypeName.INT) || type.equals(TypeName.INT.box())) {
    builder.addStatement("$N = $N.getInt($N)", field, json, key);
  } else if (type.equals(TypeName.DOUBLE) || type.equals(TypeName.DOUBLE.box())) {
    builder.addStatement("$N = $N.getDouble($N)", field, json, key);
  } else if (type.equals(TypeName.FLOAT) || type.equals(TypeName.FLOAT.box())) {
    builder.addStatement("$N = (float) $N.getDouble($N)", field, json, key);
  } else if (type.equals(TypeName.BOOLEAN) || type.equals(TypeName.BOOLEAN.box())) {
    builder.addStatement("$N = $N.getBoolean($N)", field, json, key);
  } else if (type.equals(TypeName.LONG) || type.equals(TypeName.LONG.box())) {
    builder.addStatement("$N = $N.getLong($N)", field, json, key);
  } else if (type.equals(TypeName.SHORT) || type.equals(TypeName.SHORT.box())) {
    builder.addStatement("$N = (short) $N.getInt($N)", field, json, key);
  } else if (type.equals(TypeName.BYTE) || type.equals(TypeName.BYTE.box())) {
    builder.addStatement("$N = (byte) $N.getInt($N)", field, json, key);
  } else if (type.equals(TypeName.CHAR) || type.equals(TypeName.CHAR.box())) {
    FieldSpec tempVal =
        FieldSpec.builder(String.class, nameAllocator.newName("tempVal"), Modifier.FINAL).build();
    builder.addStatement("$T $N = $N.getString($N)", tempVal.type, tempVal, json, key);
    builder.beginControlFlow("if(!$N.isEmpty())", tempVal);
    builder.addStatement("$N = $N.charAt(0)", field, tempVal);
    builder.endControlFlow();
  } else if (type.equals(ENUM)) {
    builder.addStatement("$N = $T.valueOf($N.getString($N))", field, field.type, json, key);
  } else {
    throw new IllegalStateException(String.format("supportedType [%s] with not method.", type));
  }

  return builder.build();
}
项目:auto-value-json    文件:AutoValueJsonExtension.java   
private MethodSpec generateWriteToJson(Context context, ExecutableElement writeMethodElement,
    List<JsonProperty> properties, Map<TypeMirror, FieldSpec> typeAdapters,
    NameAllocator nameAllocator) {
  Set<Modifier> modifierSet = new TreeSet<>(writeMethodElement.getModifiers());
  modifierSet.remove(ABSTRACT);
  MethodSpec.Builder builder =
      MethodSpec.methodBuilder(writeMethodElement.getSimpleName().toString())
          .addAnnotation(Override.class)
          .addModifiers(modifierSet)
          .returns(JSON_OBJ_CLASS_NAME);

  FieldSpec json = FieldSpec.builder(JSON_OBJ_CLASS_NAME, nameAllocator.newName("json")).build();
  builder.addStatement("$1T $2N = new $1T()", JSON_OBJ_CLASS_NAME, json);
  Types types = context.processingEnvironment().getTypeUtils();

  for (JsonProperty prop : properties) {
    if (prop.typeAdapter != null && typeAdapters.containsKey(prop.typeAdapter)) {

      builder.addCode(
          JsonGeneratorUtils.writeWithAdapter(typeAdapters.get(prop.typeAdapter), json, prop));
    } else {
      //TODO Discuss: Is null check needed?
      builder.beginControlFlow("try");
      if (prop.nullable()) {
        builder.beginControlFlow("if ($N() != null)", prop.methodName);
        builder.addCode(JsonGeneratorUtils.writeValue(types, prop, json));
        builder.endControlFlow();
      } else {
        builder.addCode(JsonGeneratorUtils.writeValue(types, prop, json));
      }
      builder.endControlFlow("catch($T e) {}", JSON_EXCEPTION);
    }
  }

  builder.addStatement("return $N", json);

  return builder.build();
}
项目:KiiAnnotation    文件:BuilderGenerator.java   
public static FieldSpec defaultGroupField() {
    ClassName className = ClassName.get("com.kii.cloud.storage", "KiiGroup");

    return FieldSpec
            .builder(className, "kiiGroup")
            .addModifiers(Modifier.PRIVATE)
            .build();
}
项目:ActivityBuilder    文件:BuilderUtilGenerator.java   
@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();
}
项目:vulture    文件:VultureProcessor.java   
private FieldSpec getTargetRefSpec(TypeElement originalClass) {
    ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName.get(ClassName.get(WeakReference.class), TypeName.get(originalClass.asType()));
    return FieldSpec
            .builder(parameterizedTypeName, "targetRef")
            .addModifiers(Modifier.PRIVATE, Modifier.STATIC)
            .build();
}
项目:vulture    文件:VultureProcessor.java   
private FieldSpec getHandlerFieldSpec(TypeSpec handlerSpec) {
    return FieldSpec
            .builder(PauseHandler.class, "handler")
            .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
            .initializer("new $N()", handlerSpec)
            .build();
}
项目:vulture    文件:VultureProcessor.java   
private TypeSpec getConcretePauseHandler(Map<ExecutableElement, String> methodToIdMap, Map<ExecutableElement, List<MethodParam>> methodToParams, FieldSpec targetRef) {
    return TypeSpec
            .classBuilder(ClassName.get(PauseHandler.class).simpleName() + "Impl")
            .addModifiers(Modifier.PRIVATE, Modifier.STATIC)
            .superclass(PauseHandler.class)
            .addMethod(getProcessMethodSpec(methodToIdMap, methodToParams, targetRef))
            .build();
}
项目:vulture    文件:VultureProcessor.java   
private MethodSpec getRegisterMethodSpecs(TypeElement originalClass, FieldSpec targetFieldSpec, FieldSpec handlerFieldSpec) {
    return MethodSpec
            .methodBuilder("register")
            .addModifiers(Modifier.STATIC)
            .addParameter(ParameterSpec.builder(TypeName.get(originalClass.asType()), "target").build())
            .addStatement("$N = new $T<>($L)", targetFieldSpec, WeakReference.class, "target")
            .addStatement("$N.resume()", handlerFieldSpec)
            .build();
}
项目:KiiAnnotation    文件:FieldGenerator.java   
public static FieldSpec fieldKiiObject() {
    ClassName className = ClassName.get("com.kii.cloud.storage", "KiiObject");
    return FieldSpec
            .builder(className, "kiiObject")
            .addModifiers(Modifier.PRIVATE)
            .build();
}