gpt4 book ai didi

java:强相关的类对

转载 作者:行者123 更新时间:2023-12-02 01:22:46 25 4
gpt4 key购买 nike

我有一对彼此相关的类:

Msg1 <-> Data1
Msg2 <-> Data2
...

其中所有“DataX”都扩展了父类(super class)“Data”,而“MsgX”则扩展了类“Msg”。这些父类(super class)目前(简化):

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

有什么建议吗?我已经尝试了数十种变体,添加和删除“?”、“扩展”……但它们都以某种方式失败了。

最佳答案

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>> {
M msg;
void modify( M msg ) {
this.msg = msg;
};
}

abstract class Msg<M extends Msg<M, D>, D extends Data<D, M>> {
abstract D createData();

void modifyData( D data ) {
data.modify( (M) this ); // <- you still need to cast `this` though
};
}

然后你可以像这样声明子类:

class FooData extends Data<FooData, FooMsg> {
}

class FooMsg extends Msg<FooMsg, FooData> {
@Override FooData createData() {
return new FooData();
}
}

关于java:强相关的类对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57415511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com