【发布时间】:2018-01-02 10:31:51
【问题描述】:
这是我原来的课程。
public class HierarchyTreeNode {
private String label;
private List<HierarchyTreeNode> children;
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public List<HierarchyTreeNode> getChildren() {
return children;
}
public void addChild(HierarchyTreeNode child) {
if (children == null) {
children = new ArrayList<>();
}
children.add(child);
}
}
我想在这里使用 Lombok @getter 和 @setter。 “addChild”应该简化为setter方法,子节点的初始化应该放在构造函数中。我尝试了以下方法,但无法理解如何使其工作:
public class HierarchyTreeNode {
@Getter
private String label;
private List<HierarchyTreeNode> children;
public HierarchyTreeNode() {
this.label = label;
this.children = children;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public List<HierarchyTreeNode> getChildren() {
return children;
}
@Setter
public void addChild(HierarchyTreeNode child) {
if (children == null) {
children = new ArrayList<>();
}
children.add(child);
}
}
我的控制器有以下功能:
if (!existingNodes.containsKey(childName)) {
// find node or create new node
HierarchyTreeNode node = existingNodes.get(parentName);
if (node == null) {
// new top level node
node = new HierarchyTreeNode();
node.setLabel(parentName);
root.addChild(node);
existingNodes.put(parentName, node);
}
// add child
HierarchyTreeNode child = new HierarchyTreeNode();
child.setLabel(childName);
node.addChild(child);
existingNodes.put(childName, child);
}
如何使用 lombok 来简化 addchild?
【问题讨论】:
-
你不能。
@Setter属于字段或类级别。对方法没有意义。 -
我不知道你想做什么。为什么你有一个注释和一个mutator?我会强烈建议您完全避免龙目岛,直到您更好地掌握基础知识。 AOP 真的不简单——不管 Lombok 怎么伪装。
-
如何使用 lombok 简化 addchild/ 整个类以及如何在构造函数中初始化子类?我是使用龙目岛的新手。我的问题是,如何在该类中使用 getter、setter?
-
@BoristheSpider 请查看原始课程。任何方式 Lombok 方法都可以在该类中使用?
标签: java spring-mvc getter-setter lombok