Behavior when getters generated by lombok are duplicated

environment

Verification

The behavior when getters generated by lombok are duplicated is summarized.

If the fields ʻa and ʻA exist

The fields ʻa and ʻA both generate a method calledgetA (). Which field's value will be obtained by executing getA ()? The results are as follows.

OneCharacter.java


/**Fields starting with a lowercase letter*/
@Getter
public class OneCharacter  {

	private String a = "a";

	private String A = "A";

	public void print() {
		System.out.println(getA()); //⇒"a"
	}
}

OneCharacter.java


/**Fields with uppercase letters first*/
@Getter
public class OneCharacter  {

	private String A = "A";

    private String a = "a";

	public void print() {
		System.out.println(getA()); //⇒"A"
	}
}

If the field ʻA and the method getA () `are defined

If the getter defined in the class and the getter generated by lombok have the same name, which one will be called?

The results are as follows.

OneCharacter.java


@Getter
public class OneCharacter  {

	public String getA() { return "getA()";}

	private String A = "A";

	public void print() {
		System.out.println(getA()); //⇒"getA()"
	}
}

OneCharacter.java


@Getter
public class OneCharacter  {

	private String A = "A";
    
	public String getA() { return "getA()";}

	public void print() {
		System.out.println(getA()); //⇒"getA()"
	}
}

The getters defined in the class were called regardless of the order of declaration.

Summary

Postscript

We received a comment from @inabajunmr.

The above phenomenon was described in lombok @Getter and @Setter.

You can annotate any field with @Getter and/or @Setter, to let lombok generate the default getter/setter automatically. A default getter simply returns the field, and is named getFoo if the field is called foo (or isFoo if the field's type is boolean). A default setter is named setFoo if the field is called foo, returns void, and takes 1 parameter of the same type as the field. It simply sets the field to this value.

Recommended Posts

Behavior when getters generated by lombok are duplicated
Behavior when Java annotation names are worn