实际问题似乎已解决(参见Mark Peters和jjnguy 的答案)。并且该fireActionPerformed
方法也已经被提及(参见OscarRyz 的回答),用于避免潜在的并发问题。
我想补充的是,您可以调用所有私有和受保护的方法(包括fireActionPerformed
),而无需使用反射对任何类进行子类化。首先,你得到Method
一个私有或受保护方法的反射对象method = clazz.getDeclaredMethod()
(clazz
需要是Class
声明该方法的类的对象,而不是它的子类之一(即AbstractButton.class
对于方法fireActionPerformed
,不是 JButton.class
))。然后,您调用method.setAccessible(true)
以抑制IllegalAccessException
在尝试访问私有或受保护的方法/字段时会出现的 s。最后,您调用method.invoke()
.
然而,我对反射的了解还不够,无法列出使用反射的缺点。但是,根据反射 API 跟踪,它们存在(参见“反射的缺点”部分)。
这里有一些工作代码:
// ButtonFireAction.java
import javax.swing.AbstractButton;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Method;
public class ButtonFireAction
{
public static void main(String[] args) throws ReflectiveOperationException
{
JButton button = new JButton("action command");
Class<AbstractButton> abstractClass = AbstractButton.class;
Method fireMethod;
// signature: public ActionEvent(Object source, int id, String command)
ActionEvent myActionEvent = new ActionEvent(button,
ActionEvent.ACTION_PERFORMED,
button.getActionCommand());
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
System.out.println(e.getActionCommand());
}
});
// get the Method object of protected method fireActionPerformed
fireMethod = abstractClass.getDeclaredMethod("fireActionPerformed",
ActionEvent.class);
// set accessible, so that no IllegalAccessException is thrown when
// calling invoke()
fireMethod.setAccessible(true);
// signature: invoke(Object obj, Object... args)
fireMethod.invoke(button,myActionEvent);
}
}