DynamicHookupTest.java Source code

Java tutorial

Introduction

Here is the source code for DynamicHookupTest.java

Source

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.lang.reflect.Method;
import java.util.Hashtable;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class DynamicHookupTest extends JFrame {
    DynamicActionAdapter actionAdapter = new DynamicActionAdapter();

    JLabel label = new JLabel("Ready...", JLabel.CENTER);

    int count;

    public DynamicHookupTest() {
        JButton launchButton = new JButton("Launch!");
        getContentPane().add(launchButton, "South");
        getContentPane().add(label, "Center");
        actionAdapter.hookup(launchButton, this, "launchTheMissiles");
    }

    public void launchTheMissiles() {
        label.setText("Launched: " + count++);
    }

    public static void main(String[] args) {
        JFrame f = new DynamicHookupTest();
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                System.exit(0);
            }
        });
        f.setSize(150, 150);
        f.setVisible(true);
    }
}

class DynamicActionAdapter implements ActionListener {
    Hashtable actions = new Hashtable();

    public void hookup(Object sourceObject, Object targetObject, String targetMethod) {
        actions.put(sourceObject, new Target(targetObject, targetMethod));
        invokeReflectedMethod(sourceObject, "addActionListener", new Object[] { this },
                new Class[] { ActionListener.class });
    }

    public void actionPerformed(ActionEvent e) {
        Target target = (Target) actions.get(e.getSource());
        if (target == null)
            throw new RuntimeException("unknown source");
        invokeReflectedMethod(target.object, target.methodName, null, null);
    }

    private void invokeReflectedMethod(Object target, String methodName, Object[] args, Class[] argTypes) {

        try {
            Method method = target.getClass().getMethod(methodName, argTypes);
            method.invoke(target, args);
        } catch (Exception e) {
            throw new RuntimeException("invocation problem: " + e);
        }
    }

    class Target {
        Object object;

        String methodName;

        Target(Object object, String methodName) {
            this.object = object;
            this.methodName = methodName;
        }
    }
}