2017-06-17 45 views
3

我正在使用Swing外觀&感覺使用kotlin。爲了創建一個UI,鞦韆需要有一個靜態方法createUI具有以下簽名:Kotlin @JvmStatic和意外覆蓋同伴對象

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! 

是否有解決此問題的方法案件?

+0

您是否試過'@JvmStatic override fun createUI'? – shiftpsh

+0

@shiftpsh它在對象聲明中不適用。 – dimafeng

回答

3

這是一個kotlin bug KT-12993。不幸的是,該錯誤尚未修復。只需使用實現您的ButtonUI或在和kotlin之間切換,以解決問題,如果您想讓kotlin實現您的UI邏輯。例如,您應該在和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 
} 

的科特林代碼如下:

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

IF你有超過半打的方法工具更多,你可以使用Proxy Design Pattern只是委託請求到在kotlin中實現的目標ButtonUI(許多IDE支持爲字段生成委託方法)。例如:

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()); 
    } 
} 
+0

謝謝你的回覆。我不確定你所指的錯誤是否描述了同樣的問題。我現在使用回退到java作爲解決方法,但我正在尋找一種更可靠的方法。 – dimafeng

+0

@dimafeng這是其實[bug](https://youtrack.jetbrains.com/issue/KT-12993)。 –