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


Java MethodSpec類代碼示例

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


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

示例1: checkCompiles

import com.squareup.javapoet.MethodSpec; //導入依賴的package包/類
private void checkCompiles(final MethodSpec method) {
	final TypeSpec wrapperTypeSpec = CallerDef
			.getNewCallerSubclassPrototype("Wrapper", TypeName.OBJECT)
			.addMethod(CallerDef.getNewCallMethodPrototype().build())
			.addMethod(CallerDef.getNewConstructorPrototype(TypeName.OBJECT).build())
			.addMethod(method)
			.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);
}
 
開發者ID:MatthewTamlin,項目名稱:Spyglass,代碼行數:19,代碼來源:TestSpecificValueIsAvailableMethodGenerator.java

示例2: getParseFieldMethod

import com.squareup.javapoet.MethodSpec; //導入依賴的package包/類
private MethodSpec getParseFieldMethod() {
    MethodSpec.Builder builder = MethodSpec.methodBuilder("parseField")
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC)
            .addParameter(mJsonObjectHolder.objectTypeName, "instance")
            .addParameter(String.class, "fieldName")
            .addParameter(JsonParser.class, JSON_PARSER_VARIABLE_NAME)
            .addException(IOException.class);

    int parseFieldLines = addParseFieldLines(builder);

    if (mJsonObjectHolder.hasParentClass()) {
        if (parseFieldLines > 0) {
            builder.nextControlFlow("else");
            builder.addStatement("$L.parseField(instance, fieldName, $L)", PARENT_OBJECT_MAPPER_VARIABLE_NAME, JSON_PARSER_VARIABLE_NAME);
        } else {
            builder.addStatement("$L.parseField(instance, fieldName, $L)", PARENT_OBJECT_MAPPER_VARIABLE_NAME, JSON_PARSER_VARIABLE_NAME);
        }
    }

    if (parseFieldLines > 0) {
        builder.endControlFlow();
    }

    return builder.build();
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:27,代碼來源:ObjectMapperInjector.java

示例3: makeSetMethod

import com.squareup.javapoet.MethodSpec; //導入依賴的package包/類
/**
 * 生成set方法
 * @param variable
 * @return String getS(String s)
 */
protected MethodSpec makeSetMethod(String variable) {

    //方法內的幾行code this.variable = var;
    StringBuilder builder = new StringBuilder();
    builder.append(String.format("this.%s", variable));
    builder.append(" = " + variable);

    //方法的 頭 和 尾
    return methodBuilder(
            "set" + com.androidyuan.Helper.ClsHelper.bigFirstString(variable)).addModifiers(
            PUBLIC).returns(
            TypeName.VOID)//public void setField
            .addParameter(getFiledType(variable), variable)//(String variableNames)
            .addStatement(builder.toString())// 添加方法內的幾行代碼到這裏
            .build();
}
 
開發者ID:weizongwei5,項目名稱:GeneratorX,代碼行數:22,代碼來源:CodeGenerator.java

示例4: compose

import com.squareup.javapoet.MethodSpec; //導入依賴的package包/類
public boolean compose(@NonNull final Type returnType,
                       @NonNull @RetNumber final String type,
                       @NonNull final MethodSpec.Builder builder) {
    final Class<?> output = PRIMITIVES.get(returnType.toString());

    if (RetNumber.MAX.equals(type)) {
        builder.addStatement("return $T.MAX_VALUE", output);

        return true;
    } else if (RetNumber.MIN.equals(type)) {
        builder.addStatement("return $T.MIN_VALUE", output);

        return true;
    } else if (RetNumber.MINUS_ONE.equals(type)) {
        builder.addStatement("return -1");

        return true;
    } else if (RetNumber.ZERO.equals(type)) {
        builder.addStatement("return 0");

        return true;
    }

    return false;
}
 
開發者ID:OleksandrKucherenko,項目名稱:autoproxy,代碼行數:26,代碼來源:RetNumberGenerator.java

示例5: getMethodSpec

import com.squareup.javapoet.MethodSpec; //導入依賴的package包/類
/**
 * genera il metodo di test per method di clazz
 * 
 * @param count
 * @param method
 * @param clazz
 * @param infoFromMongoDb
 * @param methodOutput
 * @return
 */
private MethodSpec getMethodSpec(int count, Method method, Class<?> clazz, Document methodInputs,
		Document methodOutput) {
	String result = getAssignmentOfMethodResult(method);
	String expected = getExpectedResultAsBooleanAssert(method, methodOutput);
	MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(method.getName() + count + TEST);
	/*
	 * for non spring test
	 */
	String invokerName = getInvokerName(method, clazz, methodInputs, methodBuilder);
	String params = getParams(method, methodBuilder, methodInputs);
	AnnotationSpec.Builder annSpecBuilder = AnnotationSpec.builder(Test.class);
	addExpectedExceptionIfAny(methodInputs, annSpecBuilder);
	AnnotationSpec annTestSpec = annSpecBuilder.build();
	methodBuilder.addAnnotation(annTestSpec)
			.addStatement(result + invokerName + ".$N(" + params + ")", method.getName())
			.addModifiers(Modifier.PUBLIC);
	methodBuilder.addStatement("$L.assertTrue(" + expected + ")", Assert.class.getName());
	methodBuilder.addJavadoc("\n");
	return methodBuilder.build();
}
 
開發者ID:sap-nocops,項目名稱:Jerkoff,代碼行數:31,代碼來源:PojoCreatorImpl.java

示例6: innerGenerateRouterInit

import com.squareup.javapoet.MethodSpec; //導入依賴的package包/類
private void innerGenerateRouterInit(MethodSpec.Builder methodBuilder)
{
    TypeSpec routerInit = TypeSpec.classBuilder(ROUTER_INIT_CLASS_NAME)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addSuperinterface(ClassName.get(ROUTER_API_PACKAGE_NAME, ROUTER_INIT_INTERFACE_NAME))
            .addMethod(methodBuilder.build())
            .build();
    try
    {
        JavaFile.builder(ROUTER_API_PACKAGE_NAME, routerInit)
                .build()
                .writeTo(mFiler);
    }
    catch (Exception e)
    {
        error("Failed to generate file %s", routerInit.name);
    }
}
 
開發者ID:kfrozen,項目名稱:DeeplinkRouter,代碼行數:19,代碼來源:DeeplinkRouterProcessor.java

示例7: processRemoterElements

import com.squareup.javapoet.MethodSpec; //導入依賴的package包/類
/**
 * Recursevely Visit extended elements
 */
private int processRemoterElements(TypeSpec.Builder classBuilder, Element element, int methodIndex, ElementVisitor elementVisitor, MethodSpec.Builder methodBuilder) {
    if (element instanceof TypeElement) {
        for (TypeMirror typeMirror : ((TypeElement) element).getInterfaces()) {
            if (typeMirror instanceof DeclaredType) {
                Element superElement = ((DeclaredType) typeMirror).asElement();
                methodIndex = processRemoterElements(classBuilder, superElement, methodIndex, elementVisitor, methodBuilder);
            }
        }
        for (Element member : element.getEnclosedElements()) {
            if (member.getKind() == ElementKind.METHOD) {
                elementVisitor.visitElement(classBuilder, member, methodIndex, methodBuilder);
                methodIndex++;
            }
        }
    }
    return methodIndex;
}
 
開發者ID:josesamuel,項目名稱:remoter,代碼行數:21,代碼來源:RemoteBuilder.java

示例8: operationMethodSpec

import com.squareup.javapoet.MethodSpec; //導入依賴的package包/類
private List<MethodSpec> operationMethodSpec(OperationModel opModel) {
    List<MethodSpec> methods = new ArrayList<>();

    if (opModel.getInputShape().isSimpleMethod()) {
        methods.add(simpleMethod(opModel));
    }

    methods.add(operationMethodSignature(model, opModel)
                        .addModifiers(Modifier.DEFAULT)
                        .addStatement("throw new $T()", UnsupportedOperationException.class)
                        .build());

    if (!opModel.isStreaming()) {
        methods.add(operationBuilderConsumer(model, opModel));
    }
    methods.addAll(streamingSimpleMethods(opModel));
    methods.addAll(paginatedMethods(opModel));

    return methods;
}
 
開發者ID:aws,項目名稱:aws-sdk-java-v2,代碼行數:21,代碼來源:SyncClientInterface.java

示例9: supplyFor

import com.squareup.javapoet.MethodSpec; //導入依賴的package包/類
@Override
public MethodSpec supplyFor(final AnnotationMirror anno) {
	final CodeBlock body = CodeBlock
			.builder()
			.addStatement(
					"return $T.getColorStateList($N(), $L)",
					AndroidClassNames.CONTEXT_COMPAT,
					CallerDef.GET_CONTEXT,
					getLiteralFromAnnotation(anno, "resId"))
			.build();

	return getBaseMethodSpec()
			.returns(AndroidClassNames.COLOR_STATE_LIST)
			.addCode(body)
			.build();
}
 
開發者ID:MatthewTamlin,項目名稱:Spyglass,代碼行數:17,代碼來源:GetDefaultMethodGenerator.java

示例10: serviceDefaultsMethod

import com.squareup.javapoet.MethodSpec; //導入依賴的package包/類
private MethodSpec serviceDefaultsMethod() {
    String requestHandlerDirectory = Utils.packageToDirectory(model.getMetadata().getFullClientPackageName());
    String requestHandlerPath = String.format("%s/execution.interceptors", requestHandlerDirectory);

    boolean crc32FromCompressedDataEnabled = model.getCustomizationConfig().isCalculateCrc32FromCompressedData();

    return MethodSpec.methodBuilder("serviceDefaults")
                     .addAnnotation(Override.class)
                     .addModifiers(Modifier.PROTECTED, Modifier.FINAL)
                     .returns(ClientConfigurationDefaults.class)
                     .addCode("return $T.builder()\n", ServiceBuilderConfigurationDefaults.class)
                     .addCode("         .defaultSignerProvider(this::defaultSignerProvider)\n")
                     .addCode("         .addRequestHandlerPath($S)\n", requestHandlerPath)
                     .addCode("         .crc32FromCompressedDataEnabled($L)\n", crc32FromCompressedDataEnabled)
                     .addCode("         .build();\n")
                     .build();
}
 
開發者ID:aws,項目名稱:aws-sdk-java-v2,代碼行數:18,代碼來源:BaseClientBuilderClass.java

示例11: create

import com.squareup.javapoet.MethodSpec; //導入依賴的package包/類
@Override
public String create() {
    MethodSpec method = MethodSpec.methodBuilder("onBind")
            .addModifiers(Modifier.PUBLIC)
            .addParameter(viewType, "target")
            .addParameter(valueType, "value")
            .returns(void.class)
            .addStatement("$N.$N(value)", "target", getPropertySetter(property))
            .build();

    TypeSpec anonymous = TypeSpec.anonymousClassBuilder("")
            .addSuperinterface(ParameterizedTypeName.get(TypeUtils.SYNC_ON_BIND, viewType, valueType))
            .addMethod(method)
            .build();

    return anonymous.toString();
}
 
開發者ID:sedstrom,項目名稱:Witch-Android,代碼行數:18,代碼來源:OnBindPropertySetter.java

示例12: generateConstructorBuilder

import com.squareup.javapoet.MethodSpec; //導入依賴的package包/類
private static MethodSpec.Builder generateConstructorBuilder(
    HashMap<String, BarricadeResponseSet> values, Messager messager) {
  MethodSpec.Builder methodBuilder = MethodSpec.constructorBuilder().addModifiers(PUBLIC);
  methodBuilder.addStatement("configs = new HashMap<>()");

  for (Map.Entry<String, BarricadeResponseSet> entry : values.entrySet()) {
    BarricadeResponseSet barricadeResponseSet = entry.getValue();

    String listName = "barricadeResponsesFor" + entry.getKey();

    methodBuilder.addStatement("$T<$T> " + listName + " = new $T<>()", List.class,
        BarricadeResponse.class, ArrayList.class);

    for (BarricadeResponse barricadeResponse : barricadeResponseSet.responses) {
      methodBuilder.addStatement(listName + ".add(new $T($L, $S, $S))", BarricadeResponse.class,
          barricadeResponse.statusCode, barricadeResponse.responseFileName,
          barricadeResponse.contentType);
    }

    methodBuilder.addStatement(
        "configs.put($S, new $T(" + listName + ", " + barricadeResponseSet.defaultIndex + "))",
        entry.getKey(), TYPE_BARRICADE_RESPONSE_SET);
  }
  return methodBuilder;
}
 
開發者ID:mutualmobile,項目名稱:Barricade,代碼行數:26,代碼來源:CodeGenerator.java

示例13: operationBaseSignature

import com.squareup.javapoet.MethodSpec; //導入依賴的package包/類
private static MethodSpec.Builder operationBaseSignature(IntermediateModel model,
                                                         OperationModel opModel,
                                                         Consumer<MethodSpec.Builder> addFirstParameter,
                                                         SimpleMethodOverload simpleMethodOverload,
                                                         String methodName) {

    TypeName responseType = ClassName.get(model.getMetadata().getFullModelPackageName(),
                                          opModel.getReturnType().getReturnType());
    TypeName returnType = opModel.hasStreamingOutput() ? STREAMING_TYPE_VARIABLE : responseType;

    final MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(methodName)
                                                       .returns(returnType)
                                                       .addModifiers(Modifier.PUBLIC)
                                                       .addJavadoc(opModel.getDocs(model, ClientType.SYNC,
                                                                                   simpleMethodOverload))
                                                       .addExceptions(getExceptionClasses(model, opModel));

    addFirstParameter.accept(methodBuilder);
    streamingMethod(methodBuilder, opModel, responseType);

    return methodBuilder;
}
 
開發者ID:aws,項目名稱:aws-sdk-java-v2,代碼行數:23,代碼來源:SyncClientInterface.java

示例14: generateDeepLinkHandler

import com.squareup.javapoet.MethodSpec; //導入依賴的package包/類
/**
 * Generate a new deep link handler implementation class with the specified package name,
 * class name and the constructor body.
 *
 * @param packageName        the name of the package to use for the generated class.
 * @param className          the name to be used for the implementation class.
 * @param constructorBuilder the constructor body builder for the class.
 */
private void generateDeepLinkHandler(String packageName, String className,
                                     MethodSpec.Builder constructorBuilder) {
    TypeSpec classObject = getClassObject(className)
            .addMethod(constructorBuilder.build())
            .build();

    JavaFile javaFile = JavaFile.builder(packageName, classObject)
            .build();

    try {
        javaFile.writeTo(processingEnv.getFiler());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
開發者ID:Fueled,項目名稱:flowr,代碼行數:24,代碼來源:DeepLinkAnnotationCompiler.java

示例15: generateRequestManagerRequestBuilderMethodOverride

import com.squareup.javapoet.MethodSpec; //導入依賴的package包/類
/**
 * Generates overrides of existing RequestManager methods so that they return our generated
 * RequestBuilder subtype.
 */
private MethodSpec generateRequestManagerRequestBuilderMethodOverride(
    ExecutableElement methodToOverride) {
   // We've already verified that this method returns a RequestBuilder and RequestBuilders have
  // exactly one type argument, so this is safe unless those assumptions change.
  TypeMirror typeArgument =
      ((DeclaredType) methodToOverride.getReturnType()).getTypeArguments().get(0);

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

  MethodSpec.Builder builder = ProcessorUtil.overriding(methodToOverride)
      .returns(generatedRequestBuilderOfType)
      .addCode(
          ProcessorUtil.generateCastingSuperCall(
              generatedRequestBuilderOfType, methodToOverride));

  for (AnnotationMirror mirror : methodToOverride.getAnnotationMirrors()) {
    builder.addAnnotation(AnnotationSpec.get(mirror));
  }
  return builder.build();
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:26,代碼來源:RequestManagerGenerator.java


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