动态代理。就是不用自己写代理类,只要实现接口就行了。
动态代理,这里介绍两种:jdk and cglib
第一个jdk
//一个接口类
public interface Book{
void read(String name);
}
//一个实现类
public class BookImpl implements Book{
@Override
public void read(String name){
System.out.println(name);
}
}
//实现一个一个代理类接口
public class MyInvocationHandler implements InvocationHandler{
private Object target;
public MyInvocationHandler(Object target){
this.target =target ;
}
@Override
public Object invoke(Object o,Method method,Object[] args)throws Throwable{
return method.invoke(target,args);
}
}
//测试方法
Public class Main{
public static void main(String args[]){
Book bookImpl = new BookImpl;
Object obj = Proxy.newProxyInstance(bookImpl.getClass,
)book,getClss().getInterface(),new myInvocation
}
cglib
//一个实现类
public class BookImpl {
@Override
public void read(String name){
System.out.println(name);
}
}
//实现一个一个代理类接口
public class MyInsterceptor implements MethodIntao{
private Object target;
public MyInvocationHandler(Object target){
this.target =target ;
}
@Override
public Object intercept(Object o,Method method,Object[] args,MethodProxy myInterce)throws Throwable{
return method.invoke(target,args);
}
}
//测试方法
Public class Main{
public static void main(String args[]){
BookImpl book = new BookImpl();
Enhancer enhancer = new Enhancer();
enhancer.setSuperClass (book.getClass);
enhancer.setCallback(new MyInterceptor(book))
BookImpl b = (BookImpl)enhancer.create();
}