Java Cyclic Generics

Zac*_*art 8 java generics

当存在循环关系时,如何为一组类获得类型安全性.我有3个类,路由器,交互器和组件这样

abstract class Router<C extends Component, I extends Interactor>
abstract class Interactor<R extends Router>
abstract class Component<I extends Interactor>
Run Code Online (Sandbox Code Playgroud)

我想确保特定路由器绑定到特定组件和特定交互器.

编辑应用程序的体系结构可确保我们为1个组件的1个交互器准确配置1个路由器.有些重用是可能的,但如果路由器A有交互器A和组件A,它将始终是那样,否则我们将定义路由器B,例如交互器A和组件B.

编辑2一个更具体的例子:我们可以拥有登录屏幕,其中包含loginscreenrouter,loginscreeninteractor和loginscreencomponent,然后是加载屏幕,该屏幕在同一结构中还有3个类.但我们不想要的是开发人员意外地将loadingscreenintector传递给loginscreenrouter

Tom*_*ine 9

每种类型都需要一个参数,包括每个类型本身.

abstract class Router<
    R extends Router<R,C,I>, C extends Component<R,C,I>, I extends Interactor<R,C,I>
> { }

abstract class Interactor<
    R extends Router<R,C,I>, C extends Component<R,C,I>, I extends Interactor<R,C,I>
> { }

abstract class Component<
    R extends Router<R,C,I>, C extends Component<R,C,I>, I extends Interactor<R,C,I>
>  { }
Run Code Online (Sandbox Code Playgroud)

我想另一种方式,我以前没有见过,是将所有的交互推送到一种类型.角度较小,但感觉不是很OO,也许会导致更多的工作.

import java.util.Set;

interface System<R extends Router, C extends Component, I extends Interactor> {
    Set<R> routers(I interactor);
    Set<R> routers(C component);
    Set<I> interactors(R router);
    Set<I> interactors(C component);
    Set<C> components(R router);
    Set<C> components(I interactor);
}

abstract class Router {}

abstract class Interactor {}

abstract class Component { }
Run Code Online (Sandbox Code Playgroud)