我可以使用包含A或List& lt; A& gt;的类型安全的映射吗? [英] Can I have a type safe map that either contains A or List<A>?
问题描述
我需要一个包含
项目对象
或
List< Item>对象
作为它的价值,我可以不用铸造就可以得到它,这有可能吗?
as its value, and I can get it out without casting, is it possible?
推荐答案
简短答案:否.
联盟类型在Java中不存在.为了进行编译时类型检查,您可以做的最接近的事情是创建一些自定义包装类的列表,这些包装类包含 , A
或 List< A>
,如下所示:
Union types don't exist in Java. The closest thing you could do in order to get compile-time type checking would be to create list of some custom wrapper class which contained either an A
or a List<A>
, something like the following:
public class UnionListWrapper<A> {
private final A item;
private final List<A> list;
public UnionListWrapper(A value) {
item = value;
list = null;
}
public UnionListWrapper(List<A> value) {
item = null;
list = value;
}
public Object getValue() {
if (item != null) return item;
else return list;
}
}
至少您不能创建此类的实例,这些实例不是 A
或 List< A>
,但是取回值仍然必须是 Object
,并带有关联的强制转换.这可能很笨拙,并且总体上可能不值得.
At least you wouldn't be able to create instances of this class that weren't either an A
or a List<A>
, but getting the value back out would still have to just be Object
, with associated casting. This could get quite clumsy, and on the whole it's probably not worth it.
在实践中,我可能只会有一个 List< Object>
,并带有一些注释,以非常谨慎地接受哪些数据类型.问题在于,甚至无法进行运行时检查(次优),因为Java的泛型擦除意味着您无法在运行时执行 instanceof A
检查(双重如此) List
的通用参数.
In practice I'd probably just have a List<Object>
with some comments around being very careful about what data types are accepted. The problem is that even run-time checks (sub-optimal) aren't going to be possible, since Java's generic erasure means that you can't do an instanceof A
check at runtime (doubly so on the generic parameter of the List
).
这篇关于我可以使用包含A或List& lt; A& gt;的类型安全的映射吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!