How to avoid manual type checking with recursive data types

Viewed 81

I'm trying to write a decoder in Java for a certain encoding format. The encoding format supports 4 types of data. string, integer, list, map. Here a list can contain any supported type as its value. Also, a map can contain any supported type as its value but the key has to be a string. My current approach is to wrap the data with an object and to use it recursively.

public class Node {
  // value could be
  // ==============
  // Integer
  // String
  // List<Node>
  // Map<String, Node>
  private final Object value;
  private final NodeType type;
}

This approach is fine. However, With this approach, I have to perform a manual type checking at the runtime. To avoid that I tried to use Java generics.

public class Node<T> {
  private final T value;
}

Now with this approach, the T's type bound should something like this.

Integer or String or List<T> or Map<String, T>

As far as I know, we cannot create such a type bound in Java. I would like to know the best approach to solve this problem.

1 Answers

You could make Node an interface with four implementations.

public interface Node<T> {
    T getValue();
    NodeType getType();
}

public class IntegerNode implements Node<Integer> {
    ...
}

public class StringNode implements Node<String> {
    ...
}

public class ListNode<T> implements Node<List<T>> {
    ...
}

public class MapNode<T> implements Node<Map<String, T>> {
    ...
}
Related