java:强相关的类对

我有一对彼此相关的课程:


Msg1 <-> Data1

Msg2 <-> Data2

...

所有“DataX”都扩展了超类“Data”,“MsgX”扩展了类“Msg”。这些超类目前(已简化):


abstract class Data< MSG extends Msg<? extends Data<MSG>>> {

       MSG msg;

       void modify( MSG msg ) {

           this.msg = msg;

       };   

}

和:


abstract class Msg< DATA extends Data<? extends Msg<DATA>>> {

    abstract DATA createData();


    void modifyData( DATA data ) {

        data.modify( this );

    };  

}

但是,这两个类 Data 和 Msg 的编译失败,语句“data.modify(this);”出现以下错误:


Msg.java:5: error: method modify in class Data<MSG> cannot be applied to given types;

            data.modify( this );

                ^

  required: CAP#1

  found: Msg<DATA>

  reason: argument mismatch; Msg<DATA> cannot be converted to CAP#1

  where DATA,MSG are type-variables:

    DATA extends Data<? extends Msg<DATA>> declared in class Msg

    MSG extends Msg<? extends Data<MSG>> declared in class Data

  where CAP#1 is a fresh type-variable:

    CAP#1 extends Msg<DATA> from capture of ? extends Msg<DATA>

1 error

有什么建议吗?我已经尝试了十分之一的变体,添加和删除“?”,“扩展”,......但他们都以某种方式失败了。


达令说
浏览 117回答 1
1回答

慕雪6442864

Java 有时就是这样🤷。基本上您需要做的是定义一个具体的类型参数,它引用回被声明的类,而不是使用通配符。我的意思是,而不是abstract class Data<M extends Msg<? extends Data<M>>> {}abstract class Msg<D extends Data<? extends Msg<D>>> {}声明为abstract class Data<D extends Data<D, M>, M extends Msg<M, D>>abstract class Msg<M extends Msg<M, D>, D extends Data<D, M>>准确地说,像这样定义基类abstract class Data<D extends Data<D, M>, M extends Msg<M, D>> {&nbsp; &nbsp; &nbsp; &nbsp;M msg;&nbsp; &nbsp; &nbsp; &nbsp;void modify( M msg ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this.msg = msg;&nbsp; &nbsp; &nbsp; &nbsp;};}abstract class Msg<M extends Msg<M, D>, D extends Data<D, M>> {&nbsp; &nbsp; abstract D createData();&nbsp; &nbsp; void modifyData( D data ) {&nbsp; &nbsp; &nbsp; &nbsp; data.modify( (M) this ); // <- you still need to cast `this` though&nbsp; &nbsp; };&nbsp;&nbsp;}然后你可以像这样声明子类:class FooData extends Data<FooData, FooMsg> {}class FooMsg extends Msg<FooMsg, FooData> {&nbsp; &nbsp; @Override FooData createData() {&nbsp; &nbsp; &nbsp; &nbsp; return new FooData();&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java