我不知道为什么我不能使用自引用泛型。
在 Java 中,我有一个自引用泛型。有很多事情(Intent
s),以及查找(解决)这些事情的策略(ResolutionStrategy
s)。
自引用Intent
类型定义如下。我想在编译时定义只能接收ResolutionStrategy
接受相同意图的类。
public interface Intent<I extends Intent<I, R>, R extends Resolution>
{
void resolve(ResolutionStrategy<I, R> strategy);
R getResolution();
}
因此,解决策略是:
public interface ResolutionStrategy<I extends Intent<I, R>, R extends Resolution>
{
R resolve(I intent);
}
因此,当我对这些Intent
s 的列表进行操作时,我并不真正关心它们是什么。但是,我确实想在我的领域模型中创建代表具体事物的特定类型。这是一个例子:
public class OrgIntent implements Intent<OrgIntent, IdentifiableResolution>
{
public final String name;
public OrgIntent(String name)
{
this.name = name;
}
@Override
public void resolve(ResolutionStrategy<OrgIntent, IdentifiableResolution> strategy)
{
// Do stuff
}
@Override
public IdentifiableResolution getResolution()
{
//Return resolution got from strategy at some point in the past
return null;
}
}
IdentifiableResolution
是一个简单而无趣的实现Resolution
。
到目前为止一切都很好。然后计划是为这些Intent
s 构建一个漂亮的图,然后迭代它们,将每个传递给 aResolutionStrategyFactory
以获得解决它们的相关策略。但是,我不能将OrgIntent
任何通用的东西添加到列表中!
private <I extends Intent<I, R>, R extends Resolution> DirectedAcyclicGraph<Intent<I, R>, DefaultEdge> buildGraph(Declaration declaration) throws CycleFoundException
{
DirectedAcyclicGraph<Intent<I, R>, DefaultEdge> dag = new DirectedAcyclicGraph<>(DefaultEdge.class);
// Does not compile
Intent<I, R> orgIntent = new OrgIntent("some name");
// Compiles, but then not a valid argument to dag.addVertex()
Intent<OrgIntent, IdentifiableResolution> orgIntent = new OrgIntent("some name");
// Compiles, but then not a valid argument to dag.addVertex()
OrgIntent orgIntent = new OrgIntent("some name");
//Then do this
dag.addVertex(orgIntent);
...
有什么想法我应该声明orgIntent
的吗?
更新
感谢@zapl,我意识到方法定义上的泛型类型参数是一个完整的红鲱鱼。
这可以编译,但大概意味着我可以以某种方式将Intent
其泛化为具有任何旧的废话作为第一个泛型类型?
private DirectedAcyclicGraph<Intent<?, ? extends Resolution>, DefaultEdge> buildGraph(Declaration declaration) throws CycleFoundException
{
DirectedAcyclicGraph<Intent<?, ? extends Resolution>, DefaultEdge> dag = new DirectedAcyclicGraph<>(DefaultEdge.class);
OrgIntent orgIntent = new OrgIntent("some name");
dag.addVertex(orgIntent);