Search code examples
javaenumsdto

How to use pass enum to DTO


I am passing a DTO whose one of the instance variable should be of type ENUM. However the enum is defined in another class, a class that creates the DTO.

A short summary:

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.
   } 

 }

Now,

  1. What should be done to share enum between CreateNode and Node ?

  2. How should the "recipient" of Node receive the node with one of the type as enum ?


Solution

  • You need to have a name for your 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
        }
    }
    

    To be able to get a Node with this NodeType set in some other class/method, you can do something like this

    // In some class
    // In some method
    public void someMethod(){
        Node nodeWithEnumType = new CreateNode().returnNode();
        // Other stuffs
    }