public class JdkProxy implements InvocationHandler{
private Trancation2 trancation;
private Ihello target;
public JdkProxy(Trancation2 trancation, Ihello target) {
this.trancation = trancation;
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
trancation.beginTrancation();
Object obj = method.invoke(target, args);
trancation.commit();
return obj;
}
}
interface Ihello{
void sayHello();
}
class IHeloImpl implements Ihello{
@Override
public void sayHello() {
System.out.println("保存人员");
}
}
class Trancation2 {
public void beginTrancation() {
System.out.println("开启事务");
}
public void commit() {
System.out.println("提交事务");
}
}
class Client2 {
public static void main(String[] args) {
Trancation2 t2 = new Trancation2();
Ihello helo = new IHeloImpl();
JdkProxy jdkProxy = new JdkProxy(t2,helo);
Ihello helloProxy = (Ihello) Proxy.newProxyInstance(helo.getClass().getClassLoader(),helo.getClass().getInterfaces(),jdkProxy);
helloProxy.sayHello();
}
}