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 Record Class for java16 #880

Closed
wants to merge 3 commits into from
Closed
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
12 changes: 10 additions & 2 deletions src/main/java/com/squareup/javapoet/MethodSpec.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
/** A generated constructor or method declaration. */
public final class MethodSpec {
static final String CONSTRUCTOR = "<init>";

static final String COMPACT_CONSTRUCTOR = "compact";
public final String name;
public final CodeBlock javadoc;
public final List<AnnotationSpec> annotations;
Expand Down Expand Up @@ -93,6 +93,8 @@ void emit(CodeWriter codeWriter, String enclosingName, Set<Modifier> implicitMod

if (isConstructor()) {
codeWriter.emit("$L($Z", enclosingName);
} else if(isCompactConstructor()){
codeWriter.emit("$L",enclosingName);
} else {
codeWriter.emit("$T $L($Z", returnType, name);
}
Expand All @@ -105,7 +107,7 @@ void emit(CodeWriter codeWriter, String enclosingName, Set<Modifier> implicitMod
firstParameter = false;
}

codeWriter.emit(")");
if(!isCompactConstructor()) codeWriter.emit(")");

if (defaultValue != null && !defaultValue.isEmpty()) {
codeWriter.emit(" default ");
Expand Down Expand Up @@ -161,6 +163,9 @@ public boolean hasModifier(Modifier modifier) {
public boolean isConstructor() {
return name.equals(CONSTRUCTOR);
}
public boolean isCompactConstructor() {
return name.equals(COMPACT_CONSTRUCTOR);
}

@Override public boolean equals(Object o) {
if (this == o) return true;
Expand Down Expand Up @@ -191,6 +196,9 @@ public static Builder methodBuilder(String name) {
public static Builder constructorBuilder() {
return new Builder(CONSTRUCTOR);
}
public static Builder CompactConstructorBuilder() {
return new Builder(COMPACT_CONSTRUCTOR);
}

/**
* Returns a new method spec builder that overrides {@code method}.
Expand Down
41 changes: 39 additions & 2 deletions src/main/java/com/squareup/javapoet/TypeSpec.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ public final class TypeSpec {
public final TypeName superclass;
public final List<TypeName> superinterfaces;
public final Map<String, TypeSpec> enumConstants;
public final Map<String, TypeName> recordArguments;
public final List<FieldSpec> fieldSpecs;
public final CodeBlock staticBlock;
public final CodeBlock initializerBlock;
Expand All @@ -76,6 +77,7 @@ private TypeSpec(Builder builder) {
this.superclass = builder.superclass;
this.superinterfaces = Util.immutableList(builder.superinterfaces);
this.enumConstants = Util.immutableMap(builder.enumConstants);
this.recordArguments = Util.immutableMap(builder.recordArguments);
this.fieldSpecs = Util.immutableList(builder.fieldSpecs);
this.staticBlock = builder.staticBlock.build();
this.initializerBlock = builder.initializerBlock.build();
Expand Down Expand Up @@ -110,6 +112,7 @@ private TypeSpec(TypeSpec type) {
this.superclass = null;
this.superinterfaces = Collections.emptyList();
this.enumConstants = Collections.emptyMap();
this.recordArguments = Collections.emptyMap();
this.fieldSpecs = Collections.emptyList();
this.staticBlock = type.staticBlock;
this.initializerBlock = type.initializerBlock;
Expand Down Expand Up @@ -148,6 +151,14 @@ public static Builder enumBuilder(ClassName className) {
return enumBuilder(checkNotNull(className, "className == null").simpleName());
}

public static Builder recordBuilder(String name) {
return new Builder(Kind.RECORD, checkNotNull(name, "name == null"), null);
}

public static Builder recordBuilder(ClassName className) {
return recordBuilder(checkNotNull(className, "className == null").simpleName());
}

public static Builder anonymousClassBuilder(String typeArgumentsFormat, Object... args) {
return anonymousClassBuilder(CodeBlock.of(typeArgumentsFormat, args));
}
Expand All @@ -164,6 +175,7 @@ public static Builder annotationBuilder(ClassName className) {
return annotationBuilder(checkNotNull(className, "className == null").simpleName());
}


public Builder toBuilder() {
Builder builder = new Builder(kind, name, anonymousTypeArguments);
builder.javadoc.add(javadoc);
Expand Down Expand Up @@ -256,7 +268,19 @@ void emit(CodeWriter codeWriter, String enumName, Set<Modifier> implicitModifier
}

codeWriter.popType();

if (kind == Kind.RECORD){
codeWriter.emit("(");
boolean firstMember = true;
for (Iterator<Map.Entry<String, TypeName>> i = recordArguments.entrySet().iterator(); i.hasNext(); ) {
// for (FieldSpec fieldSpec : fieldSpecs) {
Map.Entry<String, TypeName> entry = i.next();
codeWriter.emit(CodeBlock.builder().add("$T "+entry.getKey(),entry.getValue()).build());
// fieldSpec.emit(codeWriter, kind.implicitFieldModifiers);
if (i.hasNext()) codeWriter.emit(", ");
firstMember = false;
}
codeWriter.emit(")");
}
codeWriter.emit(" {\n");
}

Expand Down Expand Up @@ -373,6 +397,11 @@ public enum Kind {
Collections.emptySet(),
Collections.emptySet(),
Collections.emptySet()),
RECORD(
Collections.emptySet(),
Collections.emptySet(),
Collections.emptySet(),
Collections.emptySet()),

INTERFACE(
Util.immutableSet(Arrays.asList(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)),
Expand Down Expand Up @@ -419,6 +448,7 @@ public static final class Builder {
private final CodeBlock.Builder initializerBlock = CodeBlock.builder();

public final Map<String, TypeSpec> enumConstants = new LinkedHashMap<>();
public final Map<String, TypeName> recordArguments = new LinkedHashMap<>();
public final List<AnnotationSpec> annotations = new ArrayList<>();
public final List<Modifier> modifiers = new ArrayList<>();
public final List<TypeVariableName> typeVariables = new ArrayList<>();
Expand Down Expand Up @@ -608,7 +638,14 @@ public Builder addField(TypeName type, String name, Modifier... modifiers) {
public Builder addField(Type type, String name, Modifier... modifiers) {
return addField(TypeName.get(type), name, modifiers);
}

public Builder addRecord(TypeName type, String name) {
this.recordArguments.put(name,type);
return this;
}
public Builder addRecord(Type type, String name) {
this.recordArguments.put(name,TypeName.get(type));
return this;
}
public Builder addStaticBlock(CodeBlock block) {
staticBlock.beginControlFlow("static").add(block).endControlFlow();
return this;
Expand Down
51 changes: 51 additions & 0 deletions src/test/java/RecordExample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;

import javax.lang.model.element.Modifier;
import java.io.IOException;

public class RecordExample {
public static void main(String[] args) throws IOException {
TypeSpec record = TypeSpec.recordBuilder("Employee")
.addModifiers(Modifier.PUBLIC)
.addField(int.class, "empToken", Modifier.STATIC)
.addRecord(int.class, "id")
.addRecord(String.class, "firstName")
.addRecord(String.class, "lastName")
.addMethod(MethodSpec.CompactConstructorBuilder()
.addCode("if (id < 100) {\n" +
" throw new IllegalArgumentException(" +
" \"Employee Id cannot be below 100.\");\n" +
"}\n" +
"if (firstName.length() < 2) {\n" +
" throw new IllegalArgumentException(\n" +
" \"First name must be 2 characters or more.\");\n" +
"}")
.addModifiers(Modifier.PUBLIC).build())
.addMethod(MethodSpec.constructorBuilder()
.addParameter(int.class, "id")
.addParameter(String.class, "lastName")
.addStatement("this(id, firstName, null)").build())
.addMethod(MethodSpec.methodBuilder("getFullName")
.addCode("if (lastName == null)\n" +
" System.out.println(firstName());\n" +
"\n" +
"else\n" +
" System.out.println(firstName() + \" \"\n" +
" + lastName());")
.build())
.addMethod(MethodSpec.methodBuilder("generateEmployeeToken")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.returns(int.class)
.addCode("return ++empToken;")
.build())
.build();

JavaFile javaFile = JavaFile.builder("com.example.record", record)
.build();

javaFile.writeTo(System.out);
}
}