java.lang.reflect.Proxy
Dynamic Proxyを使用するメモ
インターフェースを作成
public interface Sample {
String say();
}
クラスを作成
public class SampleImpl implements Sample {
public String say() {
return "hoge";
}
}
InvocationHandlerを実装したクラスを作成
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class SampleInvocationHandler implements InvocationHandler {
private Object obj;
public SampleInvocationHandler(Object obj) {
this.obj = obj;
}
public Object invoke(Object proxy, Method mtd, Object args) {
Object res;
try {
System.out.println("before");
res = mtd.invoke(this.obj, args);
System.out.println("after");
} catch(Exception e) {
e.printStackTrace();
}
return res;
}
}
クライアントクラスを作成
import java.lang.reflect.Proxy;
public class Client {
public static void main(String[] args) throws Exception {
Sample smp = (Sample)Proxy.newProxyInstance(
SampleImpl.class.getClassLoader(),
new Class[] { Sample.class },
new SampleInvocationHandler(new SampleImpl())
);
System.out.println(smp.say());
}
}