Java lombok clone constructor

Lombok • How to Use Constructor

To use the constructor with Lombok, you can annotate your class with @AllArgsConstructor or @RequiredArgsConstructor. @AllArgsConstructor generates a constructor that takes in all the fields in the class as arguments, while @RequiredArgsConstructor generates a constructor that takes in only the final or @NonNull fields as arguments.

@AllArgsConstructor

import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; @Getter @Setter @AllArgsConstructor public class Person  private String name; private int age; > 

In the above example, Lombok will generate a constructor with two arguments, one for name and one for age.

Here is the equivalent de-Lombok (generated) code

public class Person  private String name; private int age; public Person(String name, int age)  this.name = name; this.age = age; > public String getName()  return name; > public void setName(String name)  this.name = name; > public int getAge()  return age; > public void setAge(int age)  this.age = age; > > 

You can then create an instance of Person using this constructor like this:

Person person = new Person("John", 30); 

Lombok will handle the creation of the constructor for you, saving you from having to write the boilerplate code yourself.

@RequiredArgsConstructor

The @RequiredArgsConstructor is a Lombok annotation that generates a constructor with parameters for all final fields and/or fields annotated with @NonNull in a class.

import lombok.Getter; import lombok.NonNull; import lombok.RequiredArgsConstructor; @Getter @RequiredArgsConstructor public class Car  @NonNull private final String make; @NonNull private final String model; private int year; > 

Here is the equivalent de-Lombok (generated) code

public class Car  private final String make; private final String model; private int year; public Car(final String make, final String model)  if (make == null)  throw new NullPointerException("make"); > if (model == null)  throw new NullPointerException("model"); > this.make = make; this.model = model; > public String getMake()  return this.make; > public String getModel()  return this.model; > public int getYear()  return this.year; > public void setYear(final int year)  this.year = year; > > 

As you can see, the Lombok annotations @Getter, @NonNull, and @RequiredArgsConstructor have been replaced by the constructor and explicit getter and setter methods.

In the constructor, Lombok’s @NonNull annotation has been replaced by explicit null checks, as well as an exception thrown when null values are passed to the constructor.

In the above example, Lombok will generate a constructor that takes in two arguments, make and model, which are both marked as final and @NonNull. The year field is not included in the constructor, as it is not marked as final or @NonNull.

You can then create an instance of Car using this constructor like this:

Car car = new Car("Toyota", "Camry"); 

Lombok will handle the creation of the constructor for you, saving you from having to write the boilerplate code yourself.

Note that if all the fields in a class are marked as final or @NonNull, @RequiredArgsConstructor will generate a constructor with no arguments.

In Conclusion

In conclusion, Lombok provides convenient annotations such as @AllArgsConstructor and @RequiredArgsConstructor that generate constructors for your classes. With @AllArgsConstructor, you can quickly create a constructor that takes in all the fields in the class as arguments, while @RequiredArgsConstructor generates a constructor that takes in only the final or @NonNull fields as arguments. Lombok handles the creation of the constructor, saving you from having to write the boilerplate code yourself. By using Lombok annotations, you can reduce the amount of code you need to write, making your code cleaner and more concise.

Источник

Lombok Using @With Annotations

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Introduction

Lombok is a library that helps us significantly reduce boilerplate code when writing Java applications.

In this tutorial, we’ll see how we can make copies of immutable objects with changes to only a single property using this library.

2. Usage

When working with immutable objects, which by design don’t allow setters, we may need a similar object to the current one, but with only one property different. This can be achieved using Lombok’s @With annotation:

The above annotation generates the following under the hood:

We can then use the above-generated method to create mutated copies of the original object:

User immutableUser = new User("testuser", "[email protected]", false); User authenticatedUser = immutableUser.withAuthenticated(true); assertNotSame(immutableUser, authenticatedUser); assertFalse(immutableUser.isAuthenticated()); assertTrue(authenticatedUser.isAuthenticated());

Additionally, we have the option of annotating the whole class, which will generate withX() methods for all the properties.

3. Requirements

To use the @With annotation correctly, we need to provide an all-arguments constructor. As we can see from the above example, the generated method requires this to create a clone of the original object.

We can use either Lombok’s own @AllArgsConstructor or @Value annotation to satisfy this requirement. Alternatively, we can manually provide this constructor as well while ensuring that the order of the non-static properties in the class matches that of the constructor.

We should remember that the @With annotation does nothing if used on static fields. This is because static properties are not considered part of an object’s state. Also, Lombok skips the method generation for fields that start with the $ sign.

4. Advanced Usage

Let’s investigate some advanced scenarios when using this annotation.

4.1. Abstract Classes

We can use the @With annotation on a field of an abstract class:

public abstract class Device < private final String serial; @With private final boolean isInspected; //getters, constructor >

However, we will need to provide an implementation for the generated withInspected() method. This is because Lombok will have no idea about the concrete implementations of our abstract class to create clones of it:

public class KioskDevice extends Device < @Override public Device withInspected(boolean isInspected) < return new KioskDevice(getSerial(), isInspected); >//getters, constructor >

4.2. Naming Conventions

As we identified above, Lombok will skip fields that start with the $ sign. However, if the field starts with a character, then it is title-cased, and finally, with is prefixed to the generated method.

Alternatively, if the field starts with an underscore, then with is simply prefixed to the generated method:

According to the above code, we see that only the first two variables will have withX() methods generated for them:

Holder value = new Holder("a", "b"); Holder valueModifiedA = value.withVariableA("mod-a"); Holder valueModifiedB = value.with_variableB("mod-b"); // Holder valueModifiedC = value.with$VariableC("mod-c"); not possible

4.3. Exceptions to Method Generation

We should be mindful that in addition to fields that start with the $ sign, Lombok will not generate a withX() method if it already exists in our class:

public class Stock < @With private String sku; @With private int stockCount; //prevents another withSku() method from being generated public Stock withSku(String sku) < return new Stock("mod-" + sku, stockCount); >//constructor >

In the above scenario, no new withSku() method will be generated.

Additionally, Lombok skips method generation in the following scenario:

public class Stock < @With private String sku; private int stockCount; //also prevents another withSku() method from being generated public Stock withSKU(String. sku) < return sku == null || sku.length == 0 ? new Stock("unknown", stockCount) : new Stock("mod-" + sku[0], stockCount); >//constructor >

We can notice the different naming of the withSKU() method above.

Basically, Lombok will skip method generation if:

  • The same method exists as the generated method name (ignoring case)
  • The existing method has the same number of arguments as the generated method (including var-args)

4.4. Null Validations on Generated Methods

Similar to other Lombok annotations, we can include null checks to the methods generated using the @With annotation:

@With @AllArgsConstructor public class ImprovedUser

Lombok will generate the following code for us along with the required null checks:

public ImprovedUser withUsername(@NonNull String username) < if (username == null) < throw new NullPointerException("username is marked non-null but is null"); >else < return this.username == username ? this : new ImprovedUser(username, this.emailAddress); >> public ImprovedUser withEmailAddress(@NonNull String emailAddress) < if (emailAddress == null) < throw new NullPointerException("emailAddress is marked non-null but is null"); >else < return this.emailAddress == emailAddress ? this : new ImprovedUser(this.username, emailAddress); >>

5. Conclusion

In this article, we have seen how to use Lombok’s @With annotations to generate clones of a particular object with a change in a single field.

We also learned how and when this method generation actually works, along with how to augment it with additional validations such as null checks.

As always, the code examples are available over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Читайте также:  Java working with database
Оцените статью