SqlsessionutilProxyJDK sqlsessionutilProxyJDK = new SqlsessionutilProxyJDK();
Object[] objects = {2,"在职"};
EmpService o =(EmpService) Proxy.newProxyInstance(new EmpServiceImpl().getClass().getClassLoader(), new EmpServiceImpl().getClass().getInterfaces(), new EmpServiceProxyJDK());
Method set = new EmpServiceImpl().getClass().getMethod("set", Integer.class, String.class);
sqlsessionutilProxyJDK.setObj(new EmpServiceImpl());
sqlsessionutilProxyJDK.invoke(o, set, objects);
2)简化方式:调用代理对象的相应方法
java复制代码
public class SqlsessionutilProxyJDK implements InvocationHandler {
private Object obj;
public void setObj(Object obj) {
this.obj = obj;
}
public Object proxyInstance(Object obj){
this.obj = obj;
Object o = Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);
return o;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String name = method.getName();
if ("get".startsWith(name)||"select".startsWith(name)){
Object invoke = method.invoke(obj, args);
return invoke;
}else {
try {
SqlSession session = SqlSessionUtil.getSession();
Object invoke = method.invoke(obj, args);
session.commit();
return invoke;
} catch (Exception e) {
SqlSessionUtil.rollbackSession();
throw new RuntimeException(e);
}
}
}
}