Java Code Examples for com.squareup.javapoet.MethodSpec#Builder
The following examples show how to use
com.squareup.javapoet.MethodSpec#Builder .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ExperimentListWriter.java From siberi-android with MIT License | 6 votes |
private MethodSpec createGetParams(HashMap<String,String> experimentsHashMap){ Iterator entries = experimentsHashMap.entrySet().iterator(); ClassName textUtils = ClassName.get("android.text", "TextUtils"); MethodSpec.Builder method = MethodSpec.methodBuilder("getTestNameParams"); method.returns(String.class) .addModifiers(Modifier.PUBLIC, Modifier.STATIC); StringBuilder builder = new StringBuilder("String params[] = {"); while (entries.hasNext()) { Map.Entry entry = (Map.Entry) entries.next(); builder.append((String) entry.getKey()); if (entries.hasNext()) { builder.append(","); } } builder.append("}"); method.addStatement(builder.toString()) .addStatement("return $T.join(\",\", params)",textUtils); return method.build(); }
Example 2
Source File: TupleGenerator.java From client-sdk-java with Apache License 2.0 | 6 votes |
private MethodSpec generateHashCodeSpec(int size) { MethodSpec.Builder hashCodeSpec = MethodSpec.methodBuilder("hashCode") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(int.class) .addStatement("int $L = $L.hashCode()", RESULT, VALUE + 1); for (int i = 2; i <= size; i++) { String value = "value" + i; hashCodeSpec.addStatement( "$L = 31 * $L + ($L != null ? $L.hashCode() : 0)", RESULT, RESULT, value, value); } hashCodeSpec.addStatement("return $L", RESULT); return hashCodeSpec.build(); }
Example 3
Source File: PreferenceWriter.java From simple-preferences with Apache License 2.0 | 6 votes |
private MethodSpec writeConstructor(String preferenceName, boolean useDefaultPreferences) { MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .addParameter( ParameterSpec.builder(Context.class, "context").addAnnotation(NonNull.class).build()); if (useDefaultPreferences) { constructorBuilder.addStatement( "prefs = $T.getDefaultSharedPreferences(context.getApplicationContext())", PreferenceManager.class); } else { constructorBuilder.addStatement( "prefs = context.getApplicationContext().getSharedPreferences($S, Context.MODE_PRIVATE)", preferenceName); } return constructorBuilder.build(); }
Example 4
Source File: NotNullValidatorTest.java From anno4j with Apache License 2.0 | 6 votes |
@Test public void addValueSpaceCheck() throws Exception { ParameterSpec paramS = ParameterSpec.builder(ClassName.get(String.class), "s") .build(); MethodSpec.Builder method = MethodSpec.methodBuilder("foo") .addModifiers(Modifier.PUBLIC) .addParameter(paramS) .returns(void.class); NotNullValidator validator = new NotNullValidator(); validator.addValueSpaceCheck(method, paramS, rdfsClazz); String code = method.build().code.toString(); Matcher matcher = Pattern.compile("if\\s*\\((s\\s*==\\s*null|null\\s*==\\s*s)\\)").matcher(code); assertTrue(matcher.find()); }
Example 5
Source File: InitializerSpec.java From spring-init with Apache License 2.0 | 6 votes |
private void addBeanMethods(MethodSpec.Builder builder, TypeElement type) { boolean conditional = utils.hasAnnotation(type, SpringClassNames.CONDITIONAL.toString()); if (this.hasEnabled) { builder.beginControlFlow("if ($T.enabled)", this.className); } if (conditional) { builder.addStatement("$T conditions = context.getBeanFactory().getBean($T.class)", SpringClassNames.CONDITION_SERVICE, SpringClassNames.CONDITION_SERVICE); builder.beginControlFlow("if (conditions.matches($T.class))", type); } builder.beginControlFlow("if (context.getBeanFactory().getBeanNamesForType($T.class).length==0)", type); boolean conditionsAvailable = addScannedComponents(builder, conditional); addNewBeanForConfig(builder, type); for (ExecutableElement method : getBeanMethods(type)) { conditionsAvailable |= createBeanMethod(builder, method, type, conditionsAvailable); } addResources(builder); addRegistrarInvokers(builder); builder.endControlFlow(); if (conditional) { builder.endControlFlow(); } if (this.hasEnabled) { builder.endControlFlow(); } }
Example 6
Source File: ModuleGenerator.java From nalu with Apache License 2.0 | 5 votes |
private void generateLoadHandlers(TypeSpec.Builder typeSpec) { // method must always be created! MethodSpec.Builder loadHandlersMethod = MethodSpec.methodBuilder("loadHandlers") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC); this.metaModel.getHandlers() .forEach(handler -> { String variableName = this.processorUtils.createFullClassName(handler.getPackage(), handler.getSimpleName()); loadHandlersMethod.addComment("create handler for: " + handler.getPackage() + "." + handler.getSimpleName()) .addStatement("$T $L = new $T()", ClassName.get(handler.getPackage(), handler.getSimpleName()), variableName, ClassName.get(handler.getPackage(), handler.getSimpleName())) .addStatement("$L.setContext(super.moduleContext)", variableName) .addStatement("$L.setEventBus(super.eventBus)", variableName) .addStatement("$L.setRouter(super.router)", variableName) .addStatement("$L.bind()", variableName) .addStatement("$T.get().logDetailed(\"ModuleCreator: handler >>$L<< created\", 0)", ClassName.get(ClientLogger.class), handler.getClassName()); }); typeSpec.addMethod(loadHandlersMethod.build()); }
Example 7
Source File: EntityGenerator.java From requery with Apache License 2.0 | 5 votes |
private void generateConstructors(TypeSpec.Builder builder) { // copy the existing constructors for (ExecutableElement constructor : ElementFilter.constructorsIn( typeElement.getEnclosedElements())) { // constructor params List<? extends VariableElement> parameters = constructor.getParameters(); if (!parameters.isEmpty()) { MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder(); constructorBuilder.addModifiers(constructor.getModifiers()); List<String> parameterNames = new ArrayList<>(); for (VariableElement parameter : parameters) { Modifier[] modifiers = parameter.getModifiers().toArray( new Modifier[parameter.getModifiers().size()]); String parameterName = parameter.getSimpleName().toString(); parameterNames.add(parameterName); ParameterSpec.Builder parameterBuilder = ParameterSpec.builder( TypeName.get(parameter.asType()), parameterName, modifiers); constructorBuilder.addParameter(parameterBuilder.build()); } // super parameter/arguments StringJoiner joiner = new StringJoiner(",", "(", ")"); parameterNames.forEach(joiner::add); constructorBuilder.addStatement("super" + joiner.toString()); builder.addMethod(constructorBuilder.build()); } } }
Example 8
Source File: AbstractNumberBindTransform.java From kripton with Apache License 2.0 | 5 votes |
@Override public void generateSerializeOnJackson(BindTypeContext context, MethodSpec.Builder methodBuilder, String serializerName, TypeName beanClass, String beanName, BindProperty property) { if (property.isNullable()) { methodBuilder.beginControlFlow("if ($L!=null) ", getter(beanName, beanClass, property)); } if (property.isProperty()) { methodBuilder.addStatement("fieldCount++"); } if (property.hasTypeAdapter()) { // if in collection, we need to write only the value if (property.isInCollection()) { methodBuilder.addStatement("$L.writeString($T.write(" + PRE_TYPE_ADAPTER_TO_DATA + "$L" + POST_TYPE_ADAPTER + "))", serializerName, NUMBER_UTIL_CLAZZ, TypeAdapterUtils.class, TypeUtility.typeName(property.typeAdapter.adapterClazz), getter(beanName, beanClass, property)); } else { methodBuilder.addStatement("$L.writeStringField($S, $T.write(" + PRE_TYPE_ADAPTER_TO_DATA + "$L" + POST_TYPE_ADAPTER + "))", serializerName, property.label, NUMBER_UTIL_CLAZZ, TypeAdapterUtils.class, TypeUtility.typeName(property.typeAdapter.adapterClazz), getter(beanName, beanClass, property)); } } else { // if in collection, we need to write only the value if (property.isInCollection()) { methodBuilder.addStatement("$L.writeString($T.write($L))", serializerName, NUMBER_UTIL_CLAZZ, getter(beanName, beanClass, property)); } else { methodBuilder.addStatement("$L.writeStringField($S, $T.write($L))", serializerName, property.label, NUMBER_UTIL_CLAZZ, getter(beanName, beanClass, property)); } } if (property.isNullable()) { methodBuilder.endControlFlow(); } }
Example 9
Source File: UpdateWriter.java From sqlitemagic with Apache License 2.0 | 5 votes |
private void addCallToInternalUpdate(MethodSpec.Builder builder, Set<TableElement> allTableTriggers, FormatData internalMethodCall) { builder.beginControlFlow(String.format("if (%s)", internalMethodCall.getFormat()), internalMethodCall.getArgs()); addTableTriggersSendingStatement(builder, allTableTriggers); builder.addStatement("return true") .endControlFlow() .addStatement("return false"); }
Example 10
Source File: XSDValueSpaceValidatorTest.java From anno4j with Apache License 2.0 | 5 votes |
@Test public void testUnsigned() throws Exception { BuildableRDFSClazz xsdUnsignedInt = anno4j.createObject(BuildableRDFSClazz.class, (Resource) new URIImpl(XSD.UNSIGNED_INT)); MethodSpec.Builder methodBuilder = method.toBuilder(); validator.addValueSpaceCheck(methodBuilder, param, xsdUnsignedInt); String code = methodBuilder.build().code.toString(); Matcher matcher = Pattern.compile("if\\s*\\((x\\s*<\\s*0|0\\s*>\\s*x)\\)").matcher(code); assertTrue(matcher.find()); }
Example 11
Source File: AutoValueCursorExtension.java From auto-value-cursor with Apache License 2.0 | 5 votes |
public static ImmutableMap<ClassName, String> addColumnAdaptersToMethod( MethodSpec.Builder method, List<ColumnProperty> properties) { Map<ClassName, String> columnAdapters = new LinkedHashMap<>(); NameAllocator nameAllocator = new NameAllocator(); for (ColumnProperty property : properties) { ClassName adapter = property.columnAdapter(); if (adapter != null && !columnAdapters.containsKey(adapter)) { String name = nameAllocator.newName(toLowerCase(adapter.simpleName())); method.addStatement("$1T $2L = new $1T()", adapter, name); columnAdapters.put(adapter, name); } } return ImmutableMap.copyOf(columnAdapters); }
Example 12
Source File: ActivityResultClass.java From OnActivityResult with Apache License 2.0 | 5 votes |
private void addMethodCalls(final MethodSpec.Builder result, final Set<Parameter> existingParameters, final List<MethodCall> methodCalls) { final NameAllocator nameAllocator = new NameAllocator(); for (final MethodCall methodCall : methodCalls) { final ParameterList parameterList = methodCall.getParameterList(); this.addNecessaryParameterVariables(nameAllocator, result, existingParameters, parameterList); result.addStatement("$L.$L($L)", TARGET_VARIABLE_NAME, methodCall.getMethodName(), parameterList.toString(nameAllocator)); } }
Example 13
Source File: ByteArrayBindTransform.java From kripton with Apache License 2.0 | 4 votes |
@Override public void generateSerializeOnXml(BindTypeContext context, MethodSpec.Builder methodBuilder, String serializerName, TypeName beanClass, String beanName, BindProperty property) { XmlType xmlType = property.xmlInfo.xmlType; if (property.isNullable() && !property.isInCollection()) { methodBuilder.beginControlFlow("if ($L!=null)", getter(beanName, beanClass, property)); } if (property.hasTypeAdapter()) { switch (xmlType) { case ATTRIBUTE: methodBuilder.addStatement("$L.writeAttribute($S, $T.encode(" + PRE_TYPE_ADAPTER_TO_DATA + "$L" + POST_TYPE_ADAPTER + "))", serializerName, BindProperty.xmlName(property), Base64Utils.class, TypeAdapterUtils.class, TypeUtility.typeName(property.typeAdapter.adapterClazz),getter(beanName, beanClass, property)); break; case TAG: methodBuilder.addStatement("$L.writeStartElement($S)", serializerName, BindProperty.xmlName(property)); methodBuilder.addStatement("$L.writeBinary(" + PRE_TYPE_ADAPTER_TO_DATA + "$L" + POST_TYPE_ADAPTER + ")", serializerName, TypeAdapterUtils.class, TypeUtility.typeName(property.typeAdapter.adapterClazz),getter(beanName, beanClass, property)); methodBuilder.addStatement("$L.writeEndElement()", serializerName); break; case VALUE: case VALUE_CDATA: methodBuilder.addStatement("$L.writeBinary("+PRE_TYPE_ADAPTER_TO_DATA+"$L"+POST_TYPE_ADAPTER+")", serializerName, TypeAdapterUtils.class, TypeUtility.typeName(property.typeAdapter.adapterClazz),getter(beanName, beanClass, property)); break; } } else { switch (xmlType) { case ATTRIBUTE: methodBuilder.addStatement("$L.writeAttribute($S, $T.encode($L))", serializerName, BindProperty.xmlName(property), Base64Utils.class, getter(beanName, beanClass, property)); break; case TAG: methodBuilder.addStatement("$L.writeStartElement($S)", serializerName, BindProperty.xmlName(property)); methodBuilder.addStatement("$L.writeBinary($L)", serializerName, getter(beanName, beanClass, property)); methodBuilder.addStatement("$L.writeEndElement()", serializerName); break; case VALUE: case VALUE_CDATA: methodBuilder.addStatement("$L.writeBinary($L)", serializerName, getter(beanName, beanClass, property)); break; } } if (property.isNullable() && !property.isInCollection()) { methodBuilder.endControlFlow(); } }
Example 14
Source File: ModelPersistingGenerator.java From sqlitemagic with Apache License 2.0 | 4 votes |
private static void addOperationFailedLoggingStatement(MethodSpec.Builder builder) { if (GENERATE_LOGGING) { builder.addStatement("if ($T.LOGGING_ENABLED) $T.logError(e, \"Operation failed\")", SQLITE_MAGIC, LOG_UTIL); } }
Example 15
Source File: SolidityFunctionWrapper.java From web3j with Apache License 2.0 | 4 votes |
MethodSpec buildEventTransactionReceiptFunction( String responseClassName, String functionName, List<NamedTypeName> indexedParameters, List<NamedTypeName> nonIndexedParameters) { ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName.get( ClassName.get(List.class), ClassName.get("", responseClassName)); String generatedFunctionName = "get" + Strings.capitaliseFirstLetter(functionName) + "Events"; MethodSpec.Builder transactionMethodBuilder = MethodSpec.methodBuilder(generatedFunctionName) .addModifiers(Modifier.PUBLIC) .addParameter(TransactionReceipt.class, "transactionReceipt") .returns(parameterizedTypeName); transactionMethodBuilder .addStatement( "$T valueList = extractEventParametersWithLog(" + buildEventDefinitionName(functionName) + ", " + "transactionReceipt)", ParameterizedTypeName.get(List.class, Contract.EventValuesWithLog.class)) .addStatement( "$1T responses = new $1T(valueList.size())", ParameterizedTypeName.get( ClassName.get(ArrayList.class), ClassName.get("", responseClassName))) .beginControlFlow( "for ($T eventValues : valueList)", Contract.EventValuesWithLog.class) .addStatement("$1T typedResponse = new $1T()", ClassName.get("", responseClassName)) .addCode( buildTypedResponse( "typedResponse", indexedParameters, nonIndexedParameters, false)) .addStatement("responses.add(typedResponse)") .endControlFlow(); transactionMethodBuilder.addStatement("return responses"); return transactionMethodBuilder.build(); }
Example 16
Source File: BindSharedPreferencesBuilder.java From kripton with Apache License 2.0 | 4 votes |
/** * Generate shared preference manager. * * @param elementUtils * the element utils * @param filer * the filer * @param entity * the entity * @return typeName of generated class * @throws IOException * Signals that an I/O exception has occurred. */ public static String generate(Elements elementUtils, Filer filer, PrefsEntity entity) throws IOException { com.abubusoft.kripton.common.Converter<String, String> converter = CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.LOWER_CAMEL); String beanClassName = entity.getElement().getSimpleName().toString(); String className = getBuildPreferenceName(entity); ModelAnnotation annotation = entity.getAnnotation(BindSharedPreferences.class); String sharedPreferenceName = annotation.getAttribute(AnnotationAttributeType.VALUE); boolean generateRx = entity.hasRxProperties(); boolean generateLiveData = entity.hasLiveDataProperties(); PackageElement pkg = elementUtils.getPackageOf(entity.getElement()); String packageName = pkg.isUnnamed() ? "" : pkg.getQualifiedName().toString(); AnnotationProcessorUtilis.infoOnGeneratedClasses(BindSharedPreferences.class, packageName, className); // @formatter:off builder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC) .superclass(AbstractSharedPreference.class); BindTypeContext context = new BindTypeContext(builder, TypeUtility.typeName(entity.getElement()), Modifier.PRIVATE); // @formatter:on builder.addJavadoc("This class is the shared preference binder defined for $T\n\n", entity.getElement()); JavadocUtility.generateJavadocGeneratedBy(builder); builder.addJavadoc("@see $T\n", entity.getElement()); if (StringUtils.hasText(sharedPreferenceName)) { builder.addField(FieldSpec.builder(String.class, "SHARED_PREFERENCE_NAME", Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL) .initializer("$S", converter.convert(entity.getSimpleName().toString())).addJavadoc("shared preferences typeName for $T\n", entity.getElement()).build()); } builder.addField(FieldSpec.builder(className(beanClassName), "defaultBean", Modifier.PRIVATE, Modifier.FINAL).addJavadoc("working instance of bean\n").build()); { MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("edit").addJavadoc("create an editor to modify shared preferences\n").returns(typeName("BindEditor")) .addModifiers(Modifier.PUBLIC); methodBuilder.addStatement("return new $T()", typeName("BindEditor")); builder.addMethod(methodBuilder.build()); } generateEditor(entity); generateCreate(sharedPreferenceName, beanClassName, generateRx, generateLiveData); generateConstructor(entity, sharedPreferenceName, beanClassName); generateRefresh(sharedPreferenceName, className); generateRxSupport(sharedPreferenceName, beanClassName, generateRx, entity); generateLiveDataSupport(sharedPreferenceName, beanClassName, generateLiveData, entity); generateResetMethod(entity); generateReadMethod(entity); generateWriteMethod(entity); generateSingleReadMethod(entity); // generate all needed writer and reader List<PrefsProperty> fields = entity.getCollection(); List<PrefsProperty> filteredFields = new ArrayList<>(); // we need to avoid generation of persists values for (PrefsProperty item : fields) { if (SetPrefsTransformation.isStringSet(item)) { continue; } else { filteredFields.add(item); } } // avoid to consider StringSet ManagedPropertyPersistenceHelper.generateFieldPersistance(context, filteredFields, PersistType.STRING, false, Modifier.PROTECTED); generateInstance(className); TypeSpec typeSpec = builder.build(); JavaWriterHelper.writeJava2File(filer, packageName, typeSpec); return className; }
Example 17
Source File: SerializableClassProcessor.java From fastjgame with Apache License 2.0 | 4 votes |
/** * 创建writeObject方法 */ MethodSpec.Builder newWriteMethodBuilder(DeclaredType superDeclaredType) { return MethodSpec.overriding(writeObjectMethod, superDeclaredType, typeUtils); }
Example 18
Source File: SolidityFunctionWrapper.java From web3j with Apache License 2.0 | 4 votes |
private List<TypeSpec> buildStructTypes(final List<AbiDefinition> functionDefinitions) throws ClassNotFoundException { final List<AbiDefinition.NamedType> orderedKeys = extractStructs(functionDefinitions); int structCounter = 0; final List<TypeSpec> structs = new ArrayList<>(); for (final AbiDefinition.NamedType namedType : orderedKeys) { final String internalType = namedType.getInternalType(); final String structName; if (internalType == null || internalType.isEmpty()) { structName = "Struct" + structCounter; } else { structName = internalType.substring(internalType.lastIndexOf(".") + 1); } final TypeSpec.Builder builder = TypeSpec.classBuilder(structName) .addModifiers(Modifier.PUBLIC, Modifier.STATIC); final MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addStatement( "super(" + buildStructConstructorParameterDefinition( namedType.getComponents(), useNativeJavaTypes) + ")"); final MethodSpec.Builder nativeConstructorBuilder = MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addStatement( "super(" + buildStructConstructorParameterDefinition( namedType.getComponents(), false) + ")"); for (AbiDefinition.NamedType component : namedType.getComponents()) { if (component.getType().equals("tuple")) { final ClassName typeName = structClassNameMap.get(component.structIdentifier()); builder.addField(typeName, component.getName(), Modifier.PUBLIC); constructorBuilder.addParameter(typeName, component.getName()); nativeConstructorBuilder.addParameter(typeName, component.getName()); } else { final TypeName nativeTypeName = buildTypeName(component.getType(), useJavaPrimitiveTypes); final TypeName wrappedTypeName = getWrapperType(nativeTypeName); builder.addField(wrappedTypeName, component.getName(), Modifier.PUBLIC); constructorBuilder.addParameter(wrappedTypeName, component.getName()); nativeConstructorBuilder.addParameter(nativeTypeName, component.getName()); } constructorBuilder.addStatement( "this." + component.getName() + " = " + component.getName()); nativeConstructorBuilder.addStatement( "this." + component.getName() + " = " + component.getName() + (useNativeJavaTypes && structClassNameMap.keySet().stream() .noneMatch( i -> i == component .structIdentifier()) ? ".getValue()" : "")); } builder.superclass(namedType.isDynamic() ? DynamicStruct.class : StaticStruct.class); builder.addMethod(constructorBuilder.build()); if (useNativeJavaTypes && !namedType.getComponents().isEmpty() && namedType.getComponents().stream() .anyMatch( component -> structClassNameMap.keySet().stream() .noneMatch( i -> i == component .structIdentifier()))) { builder.addMethod(nativeConstructorBuilder.build()); } structClassNameMap.put(namedType.structIdentifier(), ClassName.get("", structName)); structs.add(builder.build()); structCounter++; } return structs; }
Example 19
Source File: SqlInsertBuilder.java From kripton with Apache License 2.0 | 2 votes |
/** * Generate. * * @param classBuilder * the class builder * @param methodBuilder * the method builder * @param mapFields * the map fields * @param method * the method * @param returnType * the return type */ void generate(TypeSpec.Builder classBuilder, MethodSpec.Builder methodBuilder, boolean mapFields, SQLiteModelMethod method, TypeName returnType);
Example 20
Source File: ObjectTypeHandlerPlugin.java From raml-java-tools with Apache License 2.0 | votes |
MethodSpec.Builder additionalPropertiesGetterBuilt(ObjectPluginContext objectPluginContext, MethodSpec.Builder incoming, EventType eventType);