1、jdk动态代理
面向接口,必须有接口和实现类,增强接口中定义的方法,只能读取接口中方法上的注解
public class Test02JDKProxy {
public static void main(String[] args) {
final Dinner d = new Human("张三");
// ClassLoader loader,
ClassLoader classLoader = d.getClass().getClassLoader();
// Class<?>[] interfaces,
Class<?>[] interfaces = d.getClass().getInterfaces();
// InvocationHandler h
InvocationHandler h = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object invoke;
if ("eat".equals(method.getName())) {
System.out.println("饭前洗手");
invoke = method.invoke(d, args);
System.out.println("饭后洗碗");
} else {
invoke = method.invoke(d, args);
}
return invoke;
}
};
Dinner proxyDinner = (Dinner) Proxy.newProxyInstance(classLoader, interfaces, h);
proxyDinner.eat("包子");
// proxyDinner.drink();
}
}
interface Dinner {
void eat(String food);
void drink();
}
class Human implements Dinner {
private String name;
public Human(String name) {
this.name = name;
}
public void eat(String food) {
System.out.println(name + ",正在吃" + food);
}
public void drink() {
System.out.println("正在喝茶");
}
}
class Student implements Dinner {
private String name;
public Student(String name) {
this.name = name;
}
public void eat(String food) {
System.out.println(name + ",正在食堂吃" + food);
}
public void drink() {
System.out.println("正在喝可乐");
}
}
2、cglib动态代理
面向父类 动态的生成子类
public class Test03CglibProxy {
@Test
public void testCglibProxy() {
Person person = new Person();
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(person.getClass());
enhancer.setCallback(new MethodInterceptor() {
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
/*
Object o 生成之后的代理对象 personProxy,
Method method 父类中原本执行的方法 Person --> eat() ,
Object[] objects 方法在调用时 传入的实参数组,
MethodProxy methodProxy 子类中重写父类的方法 personProxy >>> eat()
*/
Object invokeSuper;
if ("eat".equals(method.getName())) {
// 对方法进行增强
System.out.println("吃饭前洗手");
// 子类对象方法在执行,默认会调用父类对应被重写的方法
invokeSuper = methodProxy.invokeSuper(o, objects);
System.out.println("吃饭后洗碗");
} else {
// 正常执行
invokeSuper = methodProxy.invokeSuper(o, objects);
}
return invokeSuper;
}
});
Person personProxy = (Person) enhancer.create();
// personProxy.eat("brand");
personProxy.drink();
}
}
// 被代理类
class Person {
public Person() {
}
public void eat(String food) {
System.out.println("张三正在吃" + food);
}
public void drink() {
System.out.println("正在喝茶");
}
}