使用案列:
public class TransactionInvocationHandler implements InvocationHandler{
//zs:target
private Object target;
public TransactionInvocationHandler(Object target){
this.target = target;
}
/*
*
* 该invoke方法就是 代理类的业务方法 (ls的送花方法)
*
* method:是真正实现类的业务方法(zs的送花方法)的反射方法对象
* args:是真正实现类的业务方法的参数
*
* 这个invoke既然是代理类的业务方法(ls的送花方法),代理类的业务方法的构成
* 一部分为使用成员变量(zs)实现业务逻辑
* 一部分为对于业务逻辑的扩充
*
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Connection conn = null;
Object obj = null;
try{
conn = DBUtil.getConn();
conn.setAutoCommit(false);
//业务逻辑
/*
* zs调用送花方法
*
* zs:target
* method:参数method
*
*/
obj = method.invoke(target, args);
conn.commit();
}catch(Exception e){
conn.rollback();
e.printStackTrace();
}finally{
DBUtil.myClose(conn, null, null);
}
return obj;
}
/*
* 创建一个ls对象返回
*/
public Object getProxy(){
//Proxy.newProxyInstance方法的目的是为了创建动态代理类的对象
return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
}
2.proxy代表什么意思
proxy是真实对象的真实代理对象,invoke方法可以返回调用代理对象方法的返回结果,也可以返回对象的真实代理对象(com.sun.proxy.$Proxy0)。
3.proxy参数怎么用及什么时候用
proxy参数是invoke方法的第一个参数,通常情况下我们都是返回真实对象方法的返回结果,但是我们也可以将proxy返回,proxy是真实对象的真实代理对象,我们可以通过这个返回对象对真实的对象做各种各样的操作。
4.proxy参数运行时的类型是什么
上面我们已经打印出了proxy的类型是:com.sun.proxy.$Proxy0真实的代理对象
5.为什么不用this替代
因为this代表的是InvocationHandler接口实现类本身,并不是真实的代理对象。