我正在传递一个 DTO,其实例变量之一应为 ENUM 类型。然而,枚举是在另一个类中定义的,该类创建 DTO。
简短摘要:
public class Node {
Enum nodeType; <--- should belong
Node (Enum nodeType) {
this.nodeType = nodeType;
}
}
public class CreateNode {
Enum { TEXT_NODE, ATTR_NODE };
Node returnNode() {
// return node of Enum TEXT_NODE.
}
}
现在,
如何在 CreateNode 和 Node 之间共享枚举?
Node 的“接收者”应该如何接收其中一种类型为 enum 的节点?
最佳答案
您需要为您的枚举
起一个名称。
enum NodeType { // Name of the enum is NodeType
TEXT_NODE, ATTR_NODE
}
class Node {
NodeType nodeType; // A field of type NodeType
public Node(NodeType nodeType) {
this.nodeType = nodeType;
}
}
class CreateNode {
Node returnNode() {
return new Node(NodeType.TEXT_NODE); // return the TEXT_NODE
}
}
为了能够获取在其他类/方法中设置了此 NodeType
的节点,您可以执行以下操作
// In some class
// In some method
public void someMethod(){
Node nodeWithEnumType = new CreateNode().returnNode();
// Other stuffs
}
关于java - 如何使用将枚举传递给 DTO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19673643/