限制可能实现接口的类 [英] Restrict the classes that may implement an interface
问题描述
通常来说,是否可以限制可能实现接口的类?
更详细地说,可以使用通用接口 Foo< T> ;
将其实现限制为 T
的后代: interface Foo< T> {}
class Baz extends Bar实现Foo< Bar> {} //可取的
类Baz扩展Bar实现Foo< Qux> {} //不合意的
上下文是 Foo< Bar>
对象应该以类型安全的方式转换为 Bar
对象。
耗尽所有其他来源的信息,我已经有一个强烈的预感,这是不可能的 - 但我会很高兴,如果有人可以证明其他方式!
如果不需要强制转换,那么在界面中添加一个像这样的附加方法可能就足够了:
public T getT()
如果大多数实现实际上扩展 T
,它们可以简单地返回这个
作为该方法的实现。
Generally speaking, is it possible to restrict the classes that may implement an interface?
More specifically, can a generic interface Foo<T>
restrict its implementations to descendants of T
:
interface Foo<T> {}
class Baz extends Bar implements Foo<Bar> {} // desirable
class Baz extends Bar implements Foo<Qux> {} // undesirable
The context is that Foo<Bar>
objects should be castable to Bar
objects in a type-safe way.
Having exhausted all other sources of information, I already have a strong hunch that this isn't possible—but I would be delighted if someone could prove otherwise!
If the ability to cast is not strictly necessary, then adding an additional method like this to your interface might suffice:
public T getT()
If most implementations actually extend T
, they can simply return this
as the implementation of that method.
这篇关于限制可能实现接口的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!