本文介绍了在依赖接口上强制实现参数类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些界面非常简单:

  public interface Thawed< F> 
{
F freeze();
}

public interface Frozen< T>
{
T thaw();
}

这种方式没有问题。



但现在,我如何在 Thawed 中要求 F 来实现 Frozen T Frozen 中执行解冻

我能得到的最接近的是:

 公共界面已解冻 
公共界面冻结< T延展解冻

但是这听起来非常的递归......(也适用于 Thawed and Frozen<?>

解决方案

这是正确的答案;你不能比Java类型系统中的更好。






请注意,这确实允许

  class Cat实现了Thawed< Dog> {} 
类HouseCat扩展Cat {}
类Dog实现了Frozen< HouseCat> {}

您可以通过使用两个通用参数来避免这种情况:


$ b

  public interface Thawed< F extends Frozen< T,F>,T extends Thawed< F,T>> {} 

public interface Frozen< T extends Thawed< F,T>,F extends Frozen< T,F>> {}

然而,我认为这样做太过扑朔迷人,无法使用。



它也可以允许

  class Cat实现解冻< Dog,HouseCat> {} 

类HouseCat扩展Cat {}

class Dog实现了Frozen< HouseCat,Dog> {}


These interfaces are very simple:

public interface Thawed<F>
{
    F freeze();
}

public interface Frozen<T>
{
    T thaw();
}

This works, no problem.

But now, how would I require F in Thawed to implement Frozen, and T in Frozen to implement Thawed?

The closest I could get is:

public interface Thawed<F extends Frozen<? extends Thawed<F>>>

public interface Frozen<T extends Thawed<? extends Frozen<T>>>

But that sounds quite recursive... (also works with Thawed<?> and Frozen<?>)

解决方案

That is the correct answer; you cannot get better than that within the Java type system.


Note that this does allow

class Cat implements Thawed<Dog> { }
class HouseCat extends Cat { }
class Dog implements Frozen<HouseCat> { }

You could prevent that by using two generic parameters:

public interface Thawed<F extends Frozen<T, F>, T extends Thawed<F, T>> { }

public interface Frozen<T extends Thawed<F, T>, F extends Frozen<T, F>> { }

However, I think this is too confusing to be useful.

It would also still allow

class Cat implements Thawed<Dog, HouseCat> { }

class HouseCat extends Cat { }

class Dog implements Frozen<HouseCat, Dog> { }

这篇关于在依赖接口上强制实现参数类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 07:41