使用动态代理类这里应该先写个接口,然后实现类
public interface BusinessProcessor {
public void processBusiness();
public void test();
}
public class BusinessProcessorImpl implements BusinessProcessor {
@Override
public void processBusiness() {
System.out.println("processing business.....");
}
@Override
public void test() {
System.out.println("test");
}
}
这里是个代理的实现
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class BusinessProcessorHandler implements InvocationHandler {
private Object target = null;
BusinessProcessorHandler(Object target){
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if(method.getName().equals("processBusiness")) {
System.out.println("You can do something here before process your business");
Object result = method.invoke(target, args);
System.out.println("You can do something here after process your business");
return result;
}else {
return target;
}
}
}
使用动态代理的实现类后调用的方法都会走代理
import java.lang.reflect.Proxy;
public class Test {
public static void main(String[] args) {
BusinessProcessorImpl bpimpl = new BusinessProcessorImpl();
bpimpl.processBusiness();
BusinessProcessorHandler handler = new BusinessProcessorHandler(bpimpl);
BusinessProcessor bp = (BusinessProcessor)Proxy.newProxyInstance(bpimpl.getClass().getClassLoader(), bpimpl.getClass().getInterfaces(), handler);
bp.processBusiness();
bp.test();
}
}
2.使用cglib的demo
public class Dao {
public void update() {
System.out.println("PeopleDao.update()");
}
public void select() {
System.out.println("PeopleDao.select()");
}
}
public class DaoProxy implements MethodInterceptor {
@Override
public Object intercept(Object object, Method method, Object[] objects, MethodProxy proxy) throws Throwable {
System.out.println("Before Method Invoke");
proxy.invokeSuper(object, objects);
System.out.println("After Method Invoke");
return object;
}
}
public static void main(String[] args) {
DaoProxy daoProxy = new DaoProxy();
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(Dao.class);
enhancer.setCallback(daoProxy);
Dao dao = (Dao) enhancer.create();
dao.update();
dao.select();
}