【问题标题】:How to use pass enum to DTO如何使用传递枚举到 DTO
【发布时间】:2013-10-30 04:06:49
【问题描述】:

我正在传递一个 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.
   } 

 }

现在,

  1. 如何在 CreateNode 和 Node 之间共享枚举?

  2. Node的“接收者”应该如何接收类型为枚举类型之一的节点?

【问题讨论】:

    标签: java enums dto


    【解决方案1】:

    您需要为您的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
    }
    

    【讨论】:

    • Node的“接收者”应该如何接收类型为enum的节点?
    • 看看我编辑的答案,解释如何实现。
    【解决方案2】:
    public class Node {
        CreateNode.NodeType nodeType;
    
        public Node(CreateNode.NodeType nodeType) {
            this.nodeType = nodeType;
        }
    }
    
    class CreateNode {
        enum NodeType {
            TEXT_NODE,
            ATTR_NODE
        };
    
        public Node returnNode() {
            return new Node(NodeType.TEXT_NODE);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多