cglib(继承)
public class MainTest {
static class Koukou {
public void play() {
System.out.println("一般的扣儿");
}
}
static class KoukouProxy implements MethodInterceptor {
public Object newInstall(Object object) {
return Enhancer.create(object.getClass(), this);
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
methodProxy.invokeSuper(o, objects);
System.out.println("增强版肥扣");
return null;
}
}
public static void main(String[] args) {
Koukou koukou = (Koukou)new KoukouProxy().newInstall(new Koukou());
koukou.play();
}
}
动态代理(接口)
public class MainTest {
interface Pig {
void play();
}
static class Koukou implements Pig {
public void play() {
System.out.println("一般的扣儿");
}
}
static class KoukouProxy implements InvocationHandler {
Pig pig;
public Object newInstall(Pig pig) {
this.pig = pig;
return Proxy.newProxyInstance(
pig.getClass().getClassLoader(),
pig.getClass().getInterfaces(),
this
);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
pig.play();
System.out.println("增加的扣儿");
return null;
}
}
public static void main(String[] args) {
Pig koukou = new Koukou();
koukou = (Pig) new KoukouProxy().newInstall(koukou);
koukou.play();
}
}