好的,我有一个类(我们称之为:MenuBarClass),其中包含多个 Menu 和 MenuItem。
我想为每个 MenuItem 分配一个动作侦听器,但是..而不是执行以下操作:
menuitem_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {} });
menuitem_2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {} });
menuitem_3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {} });
// ...
menuitem_N.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {} });
我希望我的代码更易于维护并且..更重要..我不希望在一个巨大的 ActionListener 类中存在很多“if”,例如:
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(menuitem_1)) {
//do stuff..
} else if (e.getSource().equals(menuitem_2)) {
//do stuff..
} else ...
}
如果可能的话我该怎么做?
有人可以帮忙吗?
您可以使用以下命令减少冗长的内容反射 http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html创建实用程序方法的 API:
package demo;
import java.awt.event.*;
import java.lang.reflect.*;
public class ListenerProxies {
private static final Class<?>[] INTERFACES = { ActionListener.class };
public static ActionListener actionListener(final Object target,
String method) {
final Method proxied = method(target, method);
InvocationHandler handler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
ActionEvent event = (ActionEvent) args[0];
return proxied.invoke(target, event);
}
};
return (ActionListener) Proxy.newProxyInstance(target.getClass()
.getClassLoader(), INTERFACES, handler);
}
private static Method method(Object target, String method) {
try {
return target.getClass().getMethod(method, ActionEvent.class);
} catch (NoSuchMethodException e) {
throw new IllegalStateException(e);
} catch (SecurityException e) {
throw new IllegalStateException(e);
}
}
}
可以这样使用:
package demo;
import static demo.ListenerProxies.actionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class Demo {
public static void main(String[] args) {
Demo test = new Demo();
JButton hello = new JButton("Say Hello");
hello.addActionListener(actionListener(test, "sayHello"));
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(hello);
frame.pack();
frame.setVisible(true);
}
public void sayHello(ActionEvent event) {
System.out.println("Hello");
}
}
这样做的缺点是缺乏编译时检查sayHello(ActionEvent)
方法存在。
性能成本可以忽略不计。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)