Skip to content
This repository has been archived by the owner on Oct 10, 2024. It is now read-only.

Add Record Class for java16 #880

Closed
wants to merge 3 commits into from
Closed

Add Record Class for java16 #880

wants to merge 3 commits into from

Conversation

shanchuanH
Copy link

I have noticed that the new version of java has provided the "record" class, so I tried to modify the original code and complete the feature of record class.
To use the record class, I added some new method.
First, to create a record class, we can use TypeSpec.recordBuilder(name of record) and use .addRecord(Type, name) to add parameter of the record.
Second, record has a special constructor called compact constructor, we can use MethodSpec.CompactConstructorBuilder() to create one.
Here is a demo to create a record class:

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())

Here is what the result looks like:

public record Employee(int id, String firstName, String lastName) {
  static int empToken;

  Employee(int id, String lastName) {
    this(id, firstName, null);
  }

  public Employee {
    if (id < 100) {
        throw new IllegalArgumentException(    "Employee Id cannot be below 100.");
    }
    if (firstName.length() < 2) {
        throw new IllegalArgumentException(
        "First name must be 2 characters or more.");
    }
  }

@shanchuanH
Copy link
Author

#829

@shanchuanH shanchuanH closed this Apr 22, 2022
@shanchuanH shanchuanH reopened this Apr 22, 2022
@shanchuanH shanchuanH reopened this May 31, 2022
@shanchuanH shanchuanH closed this Jul 29, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant