允许Java方法调用参数对象的方法';什么是子类?

允许Java方法调用参数对象的方法';什么是子类?,java,Java,我正在做一个小的大学作业。厌倦了编写三行代码来添加按钮,我编写了一个小实用程序函数: private JButton addButton(Container container, String text) { JButton button = new JButton(text); button.addActionListener(this); container.add(button); return button; } 然后当然出现了添加文本字段的实用方法

我正在做一个小的大学作业。厌倦了编写三行代码来添加按钮,我编写了一个小实用程序函数:

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
方法没有起作用。相反,抱怨
组件
没有
操作侦听器

我能看到的唯一方法是使用
MyJButton
MyJTextField
这两种方法都继承自
MyComponent
,它有一个
addActionListener
方法。简单和消除重复的最初目标是什么


如何做到这一点?我不熟悉Java和严格类型的东西

有几种方法。如果您确信您的方法
addComponent
将只作用于
JTextField
JButton
参数,那么您可以执行显式强制转换

 if (component instanceof JButton){
  ((JButton)component).addActionListener(this); 
 }
 else if (component instanceof JTextField){
  ((JTextField)component).addActionListener(this);
 }
不是很优雅,不是很好的实践,但在您的场景中可能就足够了

如果您想调用
addActionListener
,如果
组件具有该方法,您可以使用反射-但我怀疑这对于您的目标来说是过分的

PS:如果您更清楚,这将相当于第二行:

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

问题是没有一个接口公开

addActionListener(ActionListener l)
如果有,你可以做

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

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

    return component;
}
公共组件addComponent(容器容器,T组件){
addActionListener(this);
容器。添加(组件);
返回组件;
}

假设faux ActionListenable是前面提到的接口。

我想说,您当前的方法(一组类似的助手方法)与您得到的方法一样好

有些事情是不雅的,你对此无能为力

尝试组合这些方法(按照@leonbloy的回答)的风险在于,您将静态类型安全性替换为运行时类型安全性;i、 e.
ClassCastExceptions
当类型转换失败时。。。或者更糟


从语言学的角度来看,应用程序需要一种方法,用一个或多个额外的方法“修饰”现有的类层次结构,并让多态调度调用这些方法,就像使用普通实例方法一样


这可以使用Decorator模式进行模拟,但它需要一些相当重的基础设施。。。如果类层次结构没有钩子来支持内置的模式。

这将是一个不好的使用反射的地方。你只会以一种(可能)效率较低且(肯定)更脆弱的方式做同样的事情。