Lombok - how to create custom setters and apply on different member in java

你离开我真会死。 提交于 2020-01-22 02:32:11

问题


I would like to understand how to create a custom setter in Lombok and apply the setter on specific member. I have a class with 100 members, and for 50 of them I have a custom setter that check something X before I set the value, and another 50 that have a custom setter that check something Y before the I set the value. Can it be done? this is a exmple , 2 members 2 diffrent setters , this code is repeated for all members in my class :

@JsonProperty("TAC_LAC_Start_UE1")
private Integer tacLacStartUe1;

@JsonProperty("TAC_LAC_Start_UE2")
private Integer tacLacStartUe2;

@Override
public void setTacLacStartUe1(Integer tacLacStartUe1) {
    if (Objects.equals(getTacLacStartUe1(), tacLacStartUe1)) {
        return;
    }
    this.tacLacStartUe1 = tacLacStartUe1;
    if (DocKind.ORIG == docKind) {
        ((EventDocument) prepareDirtyDocument()).setTacLacStartUe1(tacLacStartUe1);
    }
}

@Override
public Integer getTacLacStartUe2() {
    return tacLacStartUe2;
}

@Override
public void setTacLacStartUe2(Integer tacLacStartUe2) {
    if (Objects.equals(getTacLacStartUe2(), tacLacStartUe2)) {
        return;
    }
    this.tacLacStartUe2 = tacLacStartUe2;
    if (DocKind.ORIG == docKind) {
        ((EventDocument) prepareDirtyDocument()).setTacLacStartUe2(tacLacStartUe2);
    }
}

回答1:


Based on the current version's documentation (https://projectlombok.org/features/GetterSetter), it doesn't seem to include a way to specify custom checks for the setter (or getter). I fear you will have to manually code each and every setter.

The same applies for the experimental @Accessor feature.




回答2:


As @Laf said, Lombok doesn't currently support this feature. However, you still can get rid of some duplicated code by extracting setters logic to the following higher-order function:

private void doSetTacLacStartUe(
        Integer oldValue,
        Integer newValue,
        Consumer<Integer> setter,
        BiConsumer<EventDocument, Integer> eventDocumentUpdater
) {
    if (Objects.equals(oldValue, newValue)) return;
    setter.accept(newValue);
    if (DocKind.ORIG == docKind)
        eventDocumentUpdater.accept((EventDocument) prepareDirtyDocument(), newValue);
}

And using it this way:

public void setTacLacStartUe1(Integer tacLacStartUe1) {
    doSetTacLacStartUe(getTacLacStartUe1(), tacLacStartUe1, it -> this.tacLacStartUe1 = it, EventDocument::setTacLacStartUe1);
}


来源:https://stackoverflow.com/questions/58630802/lombok-how-to-create-custom-setters-and-apply-on-different-member-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!