Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add static builder factory method #3074

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -844,6 +844,7 @@ private TypeSpec generateMessage(MessageType type) {
builder.addMethod(messageConstructor(nameAllocator, type, builderJavaType));

builder.addMethod(newBuilder(nameAllocator, type));
builder.addMethod(staticBuilder(type));

builder.addMethod(messageEquals(nameAllocator, type));
builder.addMethod(messageHashCode(nameAllocator, type));
Expand Down Expand Up @@ -2077,6 +2078,23 @@ private MethodSpec newBuilder(NameAllocator nameAllocator, MessageType message)
return result.build();
}

// Example:
//
// public static final Builder builder() {
// return new Builder();
// }
private MethodSpec staticBuilder(MessageType message) {
ClassName javaType = (ClassName) typeName(message.getType());
ClassName builderJavaType = javaType.nestedClass("Builder");

MethodSpec.Builder result =
MethodSpec.methodBuilder("builder")
.addModifiers(PUBLIC, STATIC, FINAL)
.returns(builderJavaType)
.addStatement("return new $1T()", builderJavaType);
return result.build();
}

private MethodSpec setter(
NameAllocator nameAllocator, TypeName builderType, OneOf oneOf, Field field) {
TypeName javaType = fieldType(field);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,26 @@ public void nestedAbstractAdapterIsStatic() throws IOException {
+ " public abstract static class AbstractBAdapter extends ProtoAdapter<String> {\n");
}

@Test
public void builderFactoryMethodIsGenerated() throws IOException {
Schema schema =
new SchemaBuilder()
.add(
Path.get("message.proto"),
""
+ "syntax = \"proto2\";\n"
+ "message SomeMessage {\n"
+ " optional string a = 1;\n"
+ "}\n")
.build();
String javaOutput = new JavaWithProfilesGenerator(schema).generateJava("SomeMessage");
assertThat(javaOutput)
.contains(
" public static final Builder builder() {\n"
+ " return new Builder();\n"
+ " }\n");
}

/** https://github.com/square/wire/issues/655 */
@Test
public void defaultValues() throws IOException {
Expand Down