2011-04-17 24 views
1

我正在做一個小型的大學作業。寫三行代碼添加按鈕被累我寫了一個小工具功能:允許Java方法調用參數對象的子類的方法嗎?

private JButton addButton(Container container, String text) { 

    JButton button = new JButton(text); 
    button.addActionListener(this); 
    container.add(button); 

    return button; 
} 

那當然沿實用的方法來添加文本框:

private JTextField addInput(Container container, int width) { 

    JTextField input = new JTextField(width); 
    input.addActionListener(this); 
    container.add(input); 

    return input; 
} 

正如你所看到的,他們幾乎完全相同。所以我試圖通過一種強大的方法來減少行數,這會增加任何其他的東西。

private Component addComponent(Container container, Component component) { 

    component.addActionListener(this); 
    container.add(component); 

    return component; 
} 

現在,我必須承認,我開始想,也許這些超小型的實用功能有點荒謬。

然而,不管,我所有的強大addComponent方法沒有奏效。相反,抱怨Component的沒有ActionListeners

我可以看到周圍,這是具有MyJButtonMyJTextField這兩者的唯一方法從MyComponent其具有addActionListener方法繼承。簡單的原始目標和消除重複被拋出窗口?

如何/應該這樣做?我是新來的Java和嚴格類型的東西!

回答

1

我想說,你現在的方法(一堆類似的輔助方法)是一樣好,你會得到。

有些東西是不雅的,而且也沒有什麼可以做的。

的努力的方法(一起@ leonbloy的答案的線)相結合的是,你替換運行時類型安全靜態類型的安全風險;即ClassCastExceptions當一個類型轉換失敗......或更糟。


從語言學的角度來看,我們需要的是一個應用程序來「裝飾」一個額外的方法,現有的類層次結構(或方法)的方式,並通過多態性調度調用的方法,就像你用普通的實例方法做。

這可以使用Decorator模式來模擬,但它需要一些相當重量級的基礎設施......如果類層次結構不具有支持內置的格局掛鉤。

1

有幾種方法。如果你肯定知道你的方法addComponent將只JTextFieldJButton參數行事,你可以做顯式轉換

if (component instanceof JButton){ 
    ((JButton)component).addActionListener(this); 
} 
else if (component instanceof JTextField){ 
    ((JTextField)component).addActionListener(this); 
} 

不是很優雅,不是很好的做法,但它可能在你的情況下就足夠了。

如果你想調用addActionListener如果Component有方法,你可以使用反射 - 但我懷疑這將是矯枉過正你的目標。

PS:在情況下,其更清楚你,這將等同於第二行:

JButton button = (JButton)component; // explicit cast -we know for sure that this is a JButton 
    button.addActionListener(this); 
+0

這將是一個不好的地方使用反射。你可能會以(可能)效率較低和(絕對)更脆弱的方式做同樣的事情。 – 2011-04-17 03:39:57

1

的問題是沒有一個公開

addActionListener(ActionListener l) 

如果接口還有,你可以做

public <T extends Component & ActionListenable> Component addComponent(Container container, T component) { 

    component.addActionListener(this); 
    container.add(component); 

    return component; 
} 

假設人造ActionListenable是上述INTERF高手。