使用 lombok 访问字段的字段
Access fields of fields using lombok
我正在使用 lombok,假设我有两个 类。
@Data
@AllArgsConstructor
class Book {
private String name;
private BookDetail bookDetail;
}
@Data
@AllArgsConstructor
public class BookDetail {
private String description;
private String author;
}
现在我可以得到这样一本书的作者了。
Book book = new Book("name1", new BookDetail("description1", "author1"));
System.out.println(book.getBookDetail().getAuthor());
这个有点多余,有没有办法像这样直接获取作者?
Book book = new Book("name1", new BookDetail("description1", "author1"));
System.out.println(book.getAuthor());
This is a bit of redundant, is there any way to get the author directly, like this?
不,龙目岛绝对没有这样的东西。最接近的是 @Singular
Lombok @Builder
feature, which is pretty cool,但对您没有帮助,因为它 1. 用于构建器,2. 仅用于集合。
我会考虑扁平化你的结构。使用 BookDetail
会使它变得更加复杂,只有当它在其他地方给我带来很大优势时我才会这样做。
另请注意,拥有一个可设置的可变字段为您提供了两种可能性,您可以如何更改 description
:通过 getBookDetail().setDescription(....)
或通过 setBookDetail(....)
。
您可能希望在 getter 和 setter 中克隆 BookDetail
(Lombok 无法为您完成)。
另一种选择是制作 BookDetail
(@Value
而不是 @Data
)并使用 @Wither
而不是 @Setter
。这使得更改 description
非常不方便
getBookDetail(getBookDetail().withDescription(....));
但有时可能值得(一般而言,不适用于实体,所以可能不适合您的情况)。如果 Lombok 支持,我会很高兴,但它不会而且可能永远不会(就像你想要的那样,它需要访问另一个 class,这在它运行的编译阶段是非常有问题的)。
我正在使用 lombok,假设我有两个 类。
@Data
@AllArgsConstructor
class Book {
private String name;
private BookDetail bookDetail;
}
@Data
@AllArgsConstructor
public class BookDetail {
private String description;
private String author;
}
现在我可以得到这样一本书的作者了。
Book book = new Book("name1", new BookDetail("description1", "author1"));
System.out.println(book.getBookDetail().getAuthor());
这个有点多余,有没有办法像这样直接获取作者?
Book book = new Book("name1", new BookDetail("description1", "author1"));
System.out.println(book.getAuthor());
This is a bit of redundant, is there any way to get the author directly, like this?
不,龙目岛绝对没有这样的东西。最接近的是 @Singular
Lombok @Builder
feature, which is pretty cool,但对您没有帮助,因为它 1. 用于构建器,2. 仅用于集合。
我会考虑扁平化你的结构。使用 BookDetail
会使它变得更加复杂,只有当它在其他地方给我带来很大优势时我才会这样做。
另请注意,拥有一个可设置的可变字段为您提供了两种可能性,您可以如何更改 description
:通过 getBookDetail().setDescription(....)
或通过 setBookDetail(....)
。
您可能希望在 getter 和 setter 中克隆 BookDetail
(Lombok 无法为您完成)。
另一种选择是制作 BookDetail
(@Value
而不是 @Data
)并使用 @Wither
而不是 @Setter
。这使得更改 description
非常不方便
getBookDetail(getBookDetail().withDescription(....));
但有时可能值得(一般而言,不适用于实体,所以可能不适合您的情况)。如果 Lombok 支持,我会很高兴,但它不会而且可能永远不会(就像你想要的那样,它需要访问另一个 class,这在它运行的编译阶段是非常有问题的)。