この記事に書いてあること
Lombokの@Dataを付けた子DTOから、親DTOの項目を含む文字列表現を作る例です。親の機密項目までログへ出さないよう、親と子で出す項目を決めます。
結論1 @Dataだけでは親のtoStringを呼ばない
子に@Dataだけを付けると、既定のtoStringは子で宣言した項目を表示します。親の文字列表現も使う場合は、子に @ToString(callSuper = true) を追加します。
結論2-@ToString(callSuper=true)なら実現可能
子に@Dataと明示的な@ToStringを併用できます。callSuper = true は親の toString() を呼びます。親がどの項目を出すかは、親側の設定に従います。

ダメな例
次のコードの ChildDefault では、子の role は表示されますが、親の userId は表示されません。
良い例
ChildWithParent は親のtoStringを呼びます。親では出力対象に印を付けた userId だけを表示するため、privateNote は出力されません。
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
public class LombokToStringExample {
@Data
@ToString(onlyExplicitlyIncluded = true)
static class ParentDto {
@ToString.Include
private final String userId;
private final String privateNote;
}
@Data
@EqualsAndHashCode(callSuper = true)
static class ChildDefault extends ParentDto {
private final String role;
ChildDefault(String userId, String privateNote, String role) {
super(userId, privateNote);
this.role = role;
}
}
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true, onlyExplicitlyIncluded = true)
static class ChildWithParent extends ParentDto {
@ToString.Include
private final String role;
ChildWithParent(String userId, String privateNote, String role) {
super(userId, privateNote);
this.role = role;
}
}
public static void main(String[] args) {
String defaultText = new ChildDefault("u-7", "hidden", "operator").toString();
String withParent = new ChildWithParent("u-7", "hidden", "operator").toString();
if (defaultText.contains("u-7") || !withParent.contains("userId=u-7")
|| !withParent.contains("role=operator") || withParent.contains("hidden")) {
throw new AssertionError(defaultText + " / " + withParent);
}
System.out.println(defaultText);
System.out.println(withParent);
}
}LombokToStringExample.ChildDefault(role=operator)
LombokToStringExample.ChildWithParent(super=LombokToStringExample.ParentDto(userId=u-7), role=operator)(callSuper=true)の注意点
親のtoStringを呼ぶ場合は、親に追加されるフィールドが出力へ意図せず載らない設定を選びます。この例では親子とも必要な出力項目を選びました。equals/hashCodeで親の項目を含める判断は、toStringの設定とは独立しています。
