I am looking to avoid some boilerplate code. I see that jdk14 has Records as shown in the example below.
https://www.logicbig.com/tutorials/core-java-tutorial/java-14-changes/records.html
How can I do something similar to Records in jdk11 ?
I am looking to avoid some boilerplate code. I see that jdk14 has Records as shown in the example below.
https://www.logicbig.com/tutorials/core-java-tutorial/java-14-changes/records.html
How can I do something similar to Records in jdk11 ?
I highly recommend Project Lombok (site here https://projectlombok.org/). From the example you listed
public record Person(String name, String gender, int age) {}
That can be done via Lombok like this
import lombok.Data
@Data
public class Person {
private String name;
private String gender;
private int age;
}
Lombox creates getters and setters, toString
, hashCode
, and a default constructor, as well as one with all the orgs.
UPDATE: It was pointed out in the comments that records are immutable. You can easily achieve this with lombok in a couple of ways. Option 1:
import lombok.Data
@Data
public class Person {
private final String name;
private final String gender;
private final int age;
}
That will add, again, the required-args constructor. @Data
does not, for relatively obvious reasons, create setters for final
fields.
Option 2 is a little more explicit:
import lombok.*;
@RequiredArgsConstructor
@EqualsAndHashCode
@Getter
public class Person {
private String name;
private String gender;
private int age;
}
You can use code generation. It's not as concise as Java 14, but better than nothing. AutoValue is pretty amazing.
import com.google.auto.value.AutoValue;
@AutoValue
abstract class Animal {
static Animal create(String name, int numberOfLegs) {
return new AutoValue_Animal(name, numberOfLegs);
}
abstract String name();
abstract int numberOfLegs();
}