gpt4 book ai didi

swing - Kotlin @JvmStatic 和伴随对象中的意外覆盖

转载 作者:行者123 更新时间:2023-12-04 19:30:00 28 4
gpt4 key购买 nike

我正在使用 kotlin 开发 Swing 外观。为了创建 UI,Swing 需要有一个静态方法 createUI带有以下签名:

class ButtonUI: BasicButtonUI() {
...
companion object {
@JvmStatic fun createUI(p0: JComponent): ComponentUI {
...
}
}
}

然后通过 Swing 代码中的反射调用它:
m = uiClass.getMethod("createUI", new Class[]{JComponent.class});

不幸的是,上面的代码不能被 kotlin 编译器编译,因为:
Error:(88, 9) Kotlin: Accidental override: The following declarations have the same JVM signature (createUI(Ljavax/swing/JComponent;)Ljavax/swing/plaf/ComponentUI;):
fun createUI(c: JComponent): ComponentUI
fun createUI(p0: JComponent!): ComponentUI!

这种情况有解决方法吗?

最佳答案

这是一个 kotlin bug KT-12993 .不幸的是,该错误尚未修复。只使用 实现你的ButtonUI或在 之间切换如果您想让 kotlin 实现您的 ui 逻辑,则使用 kotlin 来解决问题。例如,您应该定义一个 同行 之间和 Kotlin 。

java代码如下:

public class ButtonUI extends BasicButtonUI {
private ButtonUIPeer peer;

public ButtonUI(ButtonUIPeer peer) {
this.peer = peer;
}

@Override
public void installUI(JComponent c) {
peer.installUI(c, () -> super.installUI(c));
}

// override other methods ...


public static ComponentUI createUI(JComponent c) {
// create the peer which write by kotlin
// |
return new ButtonUI(new YourButtonUIPeer());
}
}


interface ButtonUIPeer {
void installUI(Component c, Runnable parentCall);
//adding other methods for the ButtonUI
}

kotlin 代码如下:
class YourButtonUIPeer : ButtonUIPeer {
override fun installUI(c: Component, parentCall: Runnable) {
// todo: implements your own ui logic
}
}

中频你有超过半打的方法来实现,你可以使用 Proxy Design Pattern只需将请求委托(delegate)给目标 ButtonUI它在 kotlin 中实现(许多 IDE 支持为字段生成委托(delegate)方法)。例如:
public class ButtonUIProxy extends BasicButtonUI {
private final BasicButtonUI target;
//1. move the cursor to here ---^
//2. press `ALT+INSERT`
//3. choose `Delegate Methods`
//4. select all public methods and then click `OK`

public ButtonUIProxy(BasicButtonUI target) {
this.target = target;
}

public static ComponentUI createUI(JComponent c){
// class created by kotlin ---v
return new ButtonUIProxy(new ButtonUI());
}
}

关于swing - Kotlin @JvmStatic 和伴随对象中的意外覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44607112/

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