Friday, December 27, 2013

Use reflection to dynamically invoke methods

This sample code uses class reflection associated with an ActionListener to dynamically invoke the specified method at runtime. The method name and parameters can be set differently under different conditions and for different source objects.

In the code, class MethodRelection has three JTextField fields and an objModified method. When any of the JTextField fields is modified, the objModified method will be called to handle the modification accordingly.

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class MethodReflection extends JFrame{
    public MethodReflection() {
        JTextField[] data = {new JTextField("Peach", 20),
                                  new JTextField("Papaya", 20),
                                  new JTextField("Mango", 20)};
        JPanel panel = new JPanel(new GridLayout(3, 1));
     
        for (int i=0; i<data.length; i++){
            try {
                data[i].addActionListener(new ObjectActionListener(this,
                                                   "objModified",
                                                   new Object[]{data[i], "Field "+(i+1)+" Modified"}
                ));
                panel.add(data[i]);
            } catch (NoSuchMethodException e){
                System.out.println(e.getMessage());
            }
        }
     
        this.add(panel);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(700, 300);
        this.pack();
    }
 
    public static void main(String[] args){
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                (new MethodReflection()).setVisible(true);
            }
        });
     
     
    }
 
    public class ObjectActionListener implements ActionListener {
        private Object methodSource = null;
        private Object[] parameters = null;
        private String methodName = null;
        private Method method = null;

        public ObjectActionListener(Object methodSource, String methodName, Object[] parameters)
                throws NoSuchMethodException, SecurityException {
            this.methodSource = methodSource;
            this.methodName = methodName;
            if (parameters == null) {
                parameters = new Object[0];
            }
            this.parameters = parameters;
            method = getMethod();
        }

        private Method getMethod() throws NoSuchMethodException {
            Class theClass = methodSource.getClass();

            Class[] paramTypes = new Class[parameters.length];
            for (int i = 0; i < parameters.length; i++) {
                paramTypes[i] = parameters[i].getClass();
            }
            return theClass.getMethod(methodName, paramTypes);
        }

        public void actionPerformed(ActionEvent event) {
            try {
                method.invoke(methodSource, parameters);
            } catch (IllegalAccessException e) {
                System.out.println(e.getMessage());
            } catch (InvocationTargetException e) {
                System.out.println(e.getMessage());
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }
 
    public void objModified(JTextField obj, String message){
            String text = obj.getText();
            System.out.println(message+": "+text);
    }
}

The code using MethodHandle to dynamically invoke method can be found here

--------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

No comments:

Post a Comment