ダイナミックプロキシクラスの使用例
戻る
任意メソッド起動時の前後でデバックメッセージを出す方法です。
::::::::::::::
DebugProxy.java(Sunのサイトより引用)
::::::::::::::
import java.lang.reflect.*;
public class DebugProxy implements java.lang.reflect.InvocationHandler {
private Object obj;
public static Object newInstance( Object obj ) {
return java.lang.reflect.Proxy.newProxyInstance(
obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(),
new DebugProxy( obj ) );
}
private DebugProxy( Object obj ) {
this.obj = obj;
}
public Object invoke( Object proxy, Method m, Object[] args )
throws Throwable {
Object result;
try {
System.out.println( "*** before method " + m.getName() );
result = m.invoke( obj, args );
} catch ( InvocationTargetException e ) {
throw e.getTargetException();
} catch ( Exception e ) {
throw new RuntimeException( "unexpected invocation exception: " +
e.getMessage() );
} finally {
System.out.println( "*** after method " + m.getName() + "\n" );
}
return result;
}
}
::::::::::::::
MyInterface.java
::::::::::::::
/**
* $Id: Proxy.html,v 1.1 2009/06/22 16:11:53 kishi Exp kishi $
*/
public interface MyInterface {
public void doSomething();
public void doExecute();
}
::::::::::::::
MyInterfaceImpl.java
::::::::::::::
import java.util.*;
/**
* $Id: Proxy.html,v 1.1 2009/06/22 16:11:53 kishi Exp kishi $
*/
public class MyInterfaceImpl implements MyInterface {
public void doSomething() {
System.out.println( this.getClass().getName() + " is saying: " + new Date() );
}
public void doExecute() {
for ( int i = 0;i < 15;i++ ) {
System.out.printf( "%2d\n", i );
}
}
/**
* 単体試験用メインメソッド
*/
public static void main( String[] args ) {
MyInterface myObj = ( MyInterface ) DebugProxy.newInstance( new MyInterfaceImpl() );
myObj.doSomething();
myObj.doExecute();
}
}
■実行結果
$ java -cp . MyInterfaceImpl
*** before method doSomething
MyInterfaceImpl is saying: Fri Feb 17 18:50:54 JST 2006
*** after method doSomething
*** before method doExecute
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
*** after method doExecute
戻る