一辆坦克,有move()方法,现在要不改变坦克类,且能加上日志。
package com.test.myproxy.dongtai;
public interface Moveable {
public void move();
}
package com.test.myproxy.dongtai;
public class Tank implements Moveable {
@Override
public void move() {
System.out.println("moving");
}
}
日志代理类:
package com.test.myproxy.dongtai;
import java.lang.reflect.InvocationHandler;
public class LoggerHandler implements InvocationHandler {
private Object obj;
public LoggerHandler(Object obj) {
super();
this.obj = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("日志开始");
Object result = method.invoke(this.obj, args);
System.out.println("日志结束");
return result;
}
}
package com.test.myproxy.dongtai;
import java.lang.reflect.InvocationHandler;
public class Client {
public static void main(String[] args) {
Moveable m = new Tank();
InvocationHandler h = new LoggerHandler(m);
//InvocationHandler th = new TranstractHandler(h);
Moveable proxy = (Moveable)Proxy.newProxyInstance(
m.getClass().getClassLoader(),
m.getClass().getInterfaces(),
h);
proxy.move();
}
}
到这里,动态代理就实现了。
但有个问题,我只能代理一个日志,不能在日志的方法上再包一层事物
事物代理:
package com.test.myproxy.dongtai;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class TranstractHandler implements InvocationHandler {
private Object obj;
public TranstractHandler(Object obj) {
super();
this.obj = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("事物开始");
Object result = method.invoke(this.obj, args);
System.out.println("插入日志表");
System.out.println("事物结束");
return result;
}
}
InvocationHandler th = new TranstractHandler(h);
Moveable proxy = (Moveable)Proxy.newProxyInstance(
m.getClass().getClassLoader(),
m.getClass().getInterfaces(),
th);
proxy.move();
这段代码会抛 Exception in thread "main" java.lang.IllegalArgumentException: object is not an instance of declaring class
这个错误。不知道怎么改。。。
已找到解决办法:
package com.test.myproxy.dongtai;
import java.lang.reflect.InvocationHandler;
public class LoggerHandler implements InvocationHandler {
private Object obj;
public LoggerHandler(Object obj) {
super();
this.obj = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("日志开始");
Object result = null;
if(this.obj instanceof InvocationHandler) {
result = ((InvocationHandler)this.obj).invoke(proxy, method, args);
} else {
result = method.invoke(this.obj, args);
}
//事物代理中同样修改
System.out.println("日志结束");
return result;
}
}