[英]How to allow a more precise return type in this use of generics?
I'm trying to model something like a "dynamic Enum " in Java. 我正在尝试对Java中的“动态枚举 ”进行建模。 There is a generic inteface
Domain
which represents a set of allowable values, and an interface Point
that represents a particular value. 有一个通用的接口
Domain
,它表示一组允许的值,还有一个接口Point
,它表示一个特定的值。 Like this: 像这样:
public interface Domain<D extends Domain<D>> {
Set<Point<D>> points();
}
public interface Point<D> { // D works a bit like a phantom type
public D type();
}
My intention is to statically forbid accidental mixing of Point
s from different Domain
types. 我的意图是静态禁止不同
Domain
类型的Point
的意外混合。
I have the following Domain
implementation: 我有以下
Domain
实现:
public final class Symbols implements Domain<Symbols> {
final Set<Point<Symbols>> symbols = new HashSet<>();
public Symbols(final Set<String> values) {
super();
for (String value : values) {
this.symbols.add(new SymbolPoint(value));
}
}
@Override
public Set<Point<Symbols>> points() {
return symbols;
}
public class SymbolPoint implements Point<Symbols> {
private final String symbol;
...
}
}
It seems to work OK, but now I've hit a roadblock. 看来工作正常,但现在遇到了障碍。 I want the
points()
method of Symbols
to return the type Set<SymbolPoint>
. 我希望
Symbols
的points()
方法返回Set<SymbolPoint>
类型。 Which of course doesn't work because Set<SymbolPoint>
is not a subtype of Set<Point<Symbols>>
. 当然哪个不起作用,因为
Set<SymbolPoint>
不是Set<Point<Symbols>>
的子类型。 How to make it work? 如何使其运作?
Your interface Domain
should accept a wildcard for its points
method. 接口
Domain
应该为其points
方法接受通配符。
interface Domain<D extends Domain<D>> {
Set<? extends Point<D>> points();
}
You can now change Set<Point<Symbols>>
to Set<SymbolPoint>
in Symbols#points
. 现在,您可以在
Symbols#points
中将Set<Point<Symbols>>
更改为Set<SymbolPoint>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.