Home Lombok Lombok @Getter @Setter and lazy getters examples

Lombok @Getter @Setter and lazy getters examples

- Advertisement -

Complete guide to explain the usage of Lombok @Getter, @Setter annotations and generating lazy getters with several examples.

1. Annotating Fields with @Getter and @Setter

Annotate any field with Lombok’s @Getter and @Setter to generate the default getter/setter automatically by Lombok. The generated getter/setter method will be public  by default. Let’s see the following side by side examples, the right side example is the delomboked java code for the left side java code.

Make sure you already installed Lombok setup for your IDE. To Setup in Eclipse or in Spring Tool Suite refer to our Lombok Maven example setup with Eclipse.

Lobmoked User.java

public class User {

	@Getter
	private Long id;
	
	@Setter
	private String username;
	
	@Getter @Setter
	private String email;
	
	@Getter @Setter
	private LocalDate lastUpdated;

}

Delomboked User.Java

// Generated by delombok at Tue Mar 31 16:03:35 SGT 2020
package com.javabydeveloper.lombok.settergetter;

import java.time.LocalDate;

public class User {
	private Long id;
	private String username;
	private String email;
	private LocalDate lastUpdated;

	public String getUsername() {
		return this.username;
	}

	public void setId(final Long id) {
		this.id = id;
	}

	public Long getId() {
		return this.id;
	}

	public void setUsername(final String username) {
		this.username = username;
	}

	public String getEmail() {
		return this.email;
	}

	public void setEmail(final String email) {
		this.email = email;
	}

	public LocalDate getLastUpdated() {
		return this.lastUpdated;
	}

	public void setLastUpdated(final LocalDate lastUpdated) {
		this.lastUpdated = lastUpdated;
	}
}

2. Annotating Class with @Getter and @Setter

You can also put a @Getter and/or @Setter annotation on a class. In this case

  1. getters and setters will be generated for all non-static fields.
  2. No setters and getters generate for static fields.
  3. No setters will be generated for final fields.

Lobmoked User.java

@Getter
@Setter
public class User {

	private Long id;

	private String username;

	private LocalDate lastUpdated;

	// no getter setter generated for static fields
	public static int maxAge = 40;

	// only getters will be generated for final fields
	public final int minAge = 20;

}

Delomboked User.Java

public class User {
	private Long id;
	private String username;
	private LocalDate lastUpdated;
	// no getter setter generated for static fields
	public static int maxAge = 40;
	// only getters will be generated for final fields
	public final int minAge = 20;

	public Long getId() {
		return this.id;
	}

	public String getUsername() {
		return this.username;
	}

	public LocalDate getLastUpdated() {
		return this.lastUpdated;
	}

	public int getMinAge() {
		return this.minAge;
	}

	public void setId(final Long id) {
		this.id = id;
	}

	public void setUsername(final String username) {
		this.username = username;
	}

	public void setLastUpdated(final LocalDate lastUpdated) {
		this.lastUpdated = lastUpdated;
	}
}

3. Changing access level for generated getters and setters

By default generated getter/setter method will be public . To change access modifier of generated getters and setters, you need to specify AccessLevel as shown in the following example. The legal access levels are PUBLICPROTECTEDPACKAGE, and PRIVATE.

Lobmoked User.java

@Getter
@Setter
public class User {

	@Setter(AccessLevel.PRIVATE)
	private Long id;

	@Getter(AccessLevel.PROTECTED)
	private String username;
	
	@Getter(AccessLevel.PACKAGE)
	private String email;

	@Getter(AccessLevel.PUBLIC)
	@Setter(AccessLevel.PRIVATE)
	private LocalDate lastUpdated;

}

Delomboked User.Java

public class User {
	private Long id;
	private String username;
	private String email;
	private LocalDate lastUpdated;

	public Long getId() {
		return this.id;
	}

	public void setUsername(final String username) {
		this.username = username;
	}

	public void setEmail(final String email) {
		this.email = email;
	}

	private void setId(final Long id) {
		this.id = id;
	}

	protected String getUsername() {
		return this.username;
	}

	String getEmail() {
		return this.email;
	}

	public LocalDate getLastUpdated() {
		return this.lastUpdated;
	}

	private void setLastUpdated(final LocalDate lastUpdated) {
		this.lastUpdated = lastUpdated;
	}
}

4. Exclude Or disable generating getters/setters

You can always manually disable getter/setter generation for any field by using the special AccessLevel.NONE access level. This lets you override the behavior of a @Getter@Setter or @Data annotation on a class.

Lobmoked User.java

@Getter
@Setter
public class User {


	@Setter(AccessLevel.NONE)
	private Long id;
	
	@Getter(AccessLevel.NONE)
	private String username;
	
	private String email;
	
	private LocalDate lastUpdated;

}

Delomboked User.Java

public class User {
	private Long id;
	private String username;
	private String email;
	private LocalDate lastUpdated;

	public Long getId() {
		return this.id;
	}

	public String getEmail() {
		return this.email;
	}

	public LocalDate getLastUpdated() {
		return this.lastUpdated;
	}

	public void setUsername(final String username) {
		this.username = username;
	}

	public void setEmail(final String email) {
		this.email = email;
	}

	public void setLastUpdated(final LocalDate lastUpdated) {
		this.lastUpdated = lastUpdated;
	}
}

5. Return Optional for Getter

Some times you may want to return Optional for your one of getter method, but you don’t want to generate setter to set Optional for the same field. In following example Lombok won’t generate getter method, writing your own getter implementation forces to Lombok not to generate it’s own.

Lobmoked User.java

@Getter
@Setter
public class User {

	private Long id;
	
	private String username;
	
	private String email;
	
	public Optional<String> getEmail() {
		return Optional.ofNullable(email);
	}
}

Delomboked User.Java

public class User {
	private Long id;
	private String username;
	private String email;

	public Optional<String> getEmail() {
		return Optional.ofNullable(email);
	}

	public Long getId() {
		return this.id;
	}

	public String getUsername() {
		return this.username;
	}

	public void setId(final Long id) {
		this.id = id;
	}

	public void setUsername(final String username) {
		this.username = username;
	}

	public void setEmail(final String email) {
		this.email = email;
	}
}

6. Getter for boolean fileds

Following example demonstrates how Lombok generates getters/setters for boolean/Boolean fields. By default Lombok generates prefix is for getters for boolean fields. To change this behavior, set property in lombok properties lombok.getter.noIsPrefix = true (default: false)

Lobmoked User.java

@Getter
@Setter
public class User {

	private Long id;
	
	private String username;
	
	private boolean active;
	
	private boolean admin;
	
	/* conflict for lombok having admin and isAdmin.
	 * Lombok generates only one accessor for first declaration
	 */
	private boolean isAdmin;
	
	// Lombok generates getCitizenOfUS()
	private Boolean citizenOfUS;
}

Delomboked User.Java

public class User {
	private Long id;
	private String username;
	private boolean active;
	private boolean admin;
	/* conflict for lombok having admin and isAdmin.
	 * Lombok generates only one accessor for first declaration
	 */
	private boolean isAdmin;
	// Lombok generates getCitizenOfUS()
	private Boolean citizenOfUS;

	public Long getId() {
		return this.id;
	}

	public String getUsername() {
		return this.username;
	}

	public boolean isActive() {
		return this.active;
	}

	public boolean isAdmin() {
		return this.admin;
	}

	public Boolean getCitizenOfUS() {
		return this.citizenOfUS;
	}

	public void setId(final Long id) {
		this.id = id;
	}

	public void setUsername(final String username) {
		this.username = username;
	}

	public void setActive(final boolean active) {
		this.active = active;
	}

	public void setAdmin(final boolean admin) {
		this.admin = admin;
	}

	public void setCitizenOfUS(final Boolean citizenOfUS) {
		this.citizenOfUS = citizenOfUS;
	}
}

7. Return this for Setters

Some times you may want to return current instance, in this case either you need write setter manually or have to enable fluent accessor for the field like following example.

Lobmoked User.java

@Getter
@Setter
public class User {

	private Long id;
	
	private String username;
	
	// returns this for setter
	@Accessors(fluent = true)
	private String email;
	
	// user created setter
	public User setUsername(String userName) {
		this.username = userName;
		return this;
	}	
}

Delomboked User.Java

public class User {
	private Long id;
	private String username;
	// returns this for setter
	private String email;

	// user created setter
	public User setUsername(String userName) {
		this.username = userName;
		return this;
	}

	public Long getId() {
		return this.id;
	}

	public String getUsername() {
		return this.username;
	}

	public boolean email() {
		return this.email;
	}

	public void setId(final Long id) {
		this.id = id;
	}

	public User email(final boolean email) {
		this.email = email;
		return this;
	}
}

8. Generate Lazy Getter

If you use @Getter(lazy=true) for the field, initialization of the value will be delayed until the getter method is called first and value will be cached upon first call and the cached results will be return for the subsequent calls. The field must be private and final. Following example demonstrates how @Getter(lazy=true) works.

public class Payment {

	@Getter
	private Long id;
	
	@Getter
	private String status = simpleDefaultStatus();

	@Getter(lazy=true)
	private final double surCharge = complexSurchargeLogic();

	private double complexSurchargeLogic() {
	
		Double surcharge = Math.PI;
		System.out.println("Called Lazy getSurcharge method");

		return surcharge;
	}
	
	private String simpleDefaultStatus() {
		System.out.println("Called EAGER getStatus method");
		return "NOT_INITIALIZED";
	}
}

Testing :

public class GetterLazyDemo {

	public static void main(String[] args) {

		Payment payment = new Payment();

		System.out.println("Eager getters called at instance creation time!");
		double sc = payment.getSurCharge();

	}
}

Output :

Called EAGER getStatus method
Eager getters called at instance creation time!
Called Lazy getSurcharge method

Lombok Generated / delomboked Payment.java :

public class Payment {
	private Long id;
	private String status = simpleDefaultStatus();
	private final java.util.concurrent.atomic.AtomicReference<Object> surCharge = new java.util.concurrent.atomic.AtomicReference<Object>();

	private double complexSurchargeLogic() {
		Double surcharge = Math.PI;
		System.out.println("Called Lazy getSurcharge method");
		return surcharge;
	}

	private String simpleDefaultStatus() {
		System.out.println("Called EAGER getStatus method");
		return "NOT_INITIALIZED";
	}

	public Long getId() {
		return this.id;
	}

	public String getStatus() {
		return this.status;
	}

	public double getSurCharge() {
		Object value = this.surCharge.get();
		if (value == null) {
			synchronized (this.surCharge) {
				value = this.surCharge.get();
				if (value == null) {
					final double actualValue = complexSurchargeLogic();
					value = actualValue;
					this.surCharge.set(value);
				}
			}
		}
		return (Double) value;
	}
}

9. Put Annotations on Lombok generated Constructors, methods and parameters

To put annotations on the generated method, you can use onMethod, onParam and onConstructor attributes for @Getter, @Setter, @AllArgsConstructor and @NoArgsConstructor like following example.

Lobmoked User.java

@Getter
@Setter
@AllArgsConstructor(
		onConstructor_= @ConstructorParameters({"id","email"}))
public class User {

	private Long id;
	
	//@Getter([email protected]__(@Deprecated)) -- JDK7
	@Getter(onMethod_= @Deprecated) // JDK8
	@Setter(onParam_ = @NonFinal )
	private String email;
	
	@Getter(onMethod_= {
			@Generated("com.javabydeveloper.lombok.settergetter.User"),
			@Deprecated
			})
	private boolean active;
}

Delomboked User.Java

public class User {
	private Long id;
	//@Getter([email protected]__(@Deprecated)) -- JDK7
	// JDK8
	private String email;
	private boolean active;

	public Long getId() {
		return this.id;
	}

	public void setId(final Long id) {
		this.id = id;
	}

	public void setActive(final boolean active) {
		this.active = active;
	}

	@ConstructorParameters({"id", "email"})
	public User(final Long id, final String email, final boolean active) {
		this.id = id;
		this.email = email;
		this.active = active;
	}

	@Deprecated
	public String getEmail() {
		return this.email;
	}

	public void setEmail(@NonFinal final String email) {
		this.email = email;
	}

	@Generated("com.javabydeveloper.lombok.settergetter.User")
	@Deprecated
	public boolean isActive() {
		return this.active;
	}
}

10. Conclusion

We have covered most of the use cases of Lombok getter and setter annotations. Also covered Lombok getter with lazy initialization. You can refer Delombok Maven example to see how looks like lombok generated code for your Lomboked classes.

You can checkout source code at github.

You might be interested in our other following Lombok Tutorials :

  1. Lombok @ToString
  2. Lombok Data
  3. Lombok @Value
  4. Lombok @Builder
  5. Lombok @NonNull
  6. Lombok @Slf4j
  7. Lombok @Singular
  8. Lombok Spring Boot Example
Satish Varma
Satish Varmahttps://javabydeveloper.com
Satish is post graduated in master of computer applications and experienced software engineer with focus on Spring, JPA, REST, TDD and web development. Also founder of javabydeveloper.com. Follow him on LinkedIn or Twitter or Facebook

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay in Touch

Categories