2009年1月14日水曜日

[Java]インタフェースのフック

このエントリーをはてなブックマークに追加
Javaでインタフェースのフックを行います.


サンプルプログラムは,GUIに表示されたボタンを押した場合のフックについて記述してあります.

[実行クラス Main.java]
import java.awt.event.ActionListener;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

import javax.swing.*;

public class Main extends JFrame{

public Main(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(200, 200, 200, 200);
setVisible(true);
JPanel p = new JPanel();

InvocationHandler handler = new MyInvocationHandler(new MyListener());
ActionListener action = (ActionListener) Proxy.newProxyInstance(MyListener.class.getClassLoader(), new Class[]{ActionListener.class}, handler);

JButton btn = new JButton("push");
btn.addActionListener(action);
btn.setActionCommand("btn");

p.add(btn);
add(p);
}

public static void main(String[] args) {
new Main();
}
}



[イベントリスナー MyListener,java]
import java.awt.event.*;

public class MyListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("btn")){
System.out.println("push");
}
}
}




[インボケーションハンドラー MyInvocationHandler.java]
import java.awt.event.ActionListener;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class MyInvocationHandler implements InvocationHandler {

private ActionListener action;

public MyInvocationHandler(ActionListener action) {
this.action = action;
}

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result;
System.out.println("前処理");
result = method.invoke(action, args);
System.out.println("後処理");
return result;
}
}



GUIで表示されたボタンを押した際の処理結果は下記の様になります.
前処理
push
後処理