简体   繁体   English

如何避免使用递归数据类型进行手动类型检查

[英]How to avoid manual type checking with recursive data types

I'm trying to write a decoder in Java for a certain encoding format.我正在尝试在 Java 中为某种编码格式编写解码器。 The encoding format supports 4 types of data.编码格式支持 4 种类型的数据。 string, integer, list, map .字符串,integer,列表,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.此外,map 可以包含任何支持的类型作为其值,但键必须是字符串。 My current approach is to wrap the data with an object and to use it recursively.我目前的方法是用 object 包装数据并递归使用它。

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.为了避免这种情况,我尝试使用 Java generics。

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

Now with this approach, the T's type bound should something like this.现在使用这种方法,T 的类型绑定应该是这样的。

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

As far as I know, we cannot create such a type bound in Java.据我所知,我们无法在 Java 中创建这样的类型绑定。 I would like to know the best approach to solve this problem.我想知道解决这个问题的最佳方法。

You could make Node an interface with four implementations.您可以使Node成为具有四个实现的接口。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM