A practical problem has been resolved, it seems (see Mark Peters and jjnguy's answers). And the fireActionPerformed method fireActionPerformed also been mentioned (see OscarRyz answer ) to avoid potential concurrency issues.
What I wanted to add is that you can call all private and protected methods (including fireActionPerformed ), without having to subclass any classes using reflection. First, you get a Method object to reflect a private or protected method using method = clazz.getDeclaredMethod() ( clazz must be a Class object of the class that declares the method, and not one of its subclasses (i.e. AbstractButton.class for method fireActionPerformed , not JButton.class )). Then you call method.setAccessible(true) to suppress the IllegalAccessException , which otherwise occurs when you try to access private or protected methods / fields. Finally, you call method.invoke() .
I donβt know enough about reflection to be able to list the disadvantages of using reflection. They exist, however, in accordance with the Reflection API (see the "Disadvantages of Reflection" section).
Here is the working code:
// 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); } }
mkdrive2 May 23 '14 at 20:36 2014-05-23 20:36
source share