在项目的使用过程中遇到一个奇怪的问题,剥除所有的逻辑之后,可还原如下示例:
public class Test {
private boolean isTest;
private boolean test1;
private int getI;
public static void main(String[] args) {
Test test = new Test();
test.setTest(true);
test.setTest1(false);
test.setGetI(1);
boolean result = test.isTest;
System.out.println(JSON.toJSONString(test));
}
}
上面的类中有两个boolean型字段isTest和test1。按照常理输出的也应是这两个字段,我们看一下:
{"getI":1,"test":true,"test1":false}
我们可以看到字段名发生了改变,isTest变为了test。为什么会这样呢?研究了一下lombok生成set和get函数的源码,我们看一下编译后的class文件:
public class Test {
private boolean isTest;
private boolean test1;
private int getI;
public static void main(String[] args) {
Test test = new Test();
test.setTest(true);
test.setTest1(false);
test.setGetI(1);
boolean result = test.isTest;
System.out.println(JSON.toJSONString(test));
}
public Test() {
}
public boolean isTest() {
return this.isTest;
}
public boolean isTest1() {
return this.test1;
}
public int getGetI() {
return this.getI;
}
public void setTest(boolean isTest) {
this.isTest = isTest;
}
public void setTest1(boolean test1) {
this.test1 = test1;
}
public void setGetI(int getI) {
this.getI = getI;
}
public boolean equals(Object o) {
if(o == this) {
return true;
} else if(!(o instanceof Test)) {
return false;
} else {
Test other = (Test)o;
return !other.canEqual(this)?false:(this.isTest() != other.isTest()?false:(this.isTest1() != other.isTest1()?false:this.getGetI() == other.getGetI()));
}
}
protected boolean canEqual(Object other) {
return other instanceof Test;
}
public int hashCode() {
boolean PRIME = true;
byte result = 1;
int result1 = result * 59 + (this.isTest()?79:97);
result1 = result1 * 59 + (this.isTest1()?79:97);
result1 = result1 * 59 + this.getGetI();
return result1;
}
public String toString() {
return "Test(isTest=" + this.isTest() + ", test1=" + this.isTest1() + ", getI=" + this.getGetI() + ")";
}
}
从上面可以看出lombok生成boolean类型的get函数以is开头,且去掉了字段的is,把字段当成了test。 而对于其他类型的字段,生成的get函数虽然以get开头,但没有这个问题。如上面的getI字段,生成的get函数名是 getGetI(),所以输出的字段名还是 getI。