通过InvocationHandler实现动态代理需要被代理类为interface,才可以使用JDK代理。否则就需要使用cglib方式进行动态代理设置。具体使用方式如下:
public class DynamicProxy implements InvocationHandler {
/** 被代理对象 **/
private Object obj;
DynamicProxy (Object obj){
this.obj = obj;
}
public static Object newInstance(Object obj){
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(), new DynamicProxy (obj));
}
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
try {
//自定义业务
......
return m.invoke(obj, args);
}
catch(InvocationTargetException e) {
throw e.getTargetException();
} finally {
;
}
}
}
使用方式:
public static void main(String[] args){
Interface interfaceImpl = new InterfaceImpl();
Interface interface = (Interface)DynamicProxy.newInstance(interfaceImpl);
}