Java Proxy.newProxyInstance动态代理
2021-01-02 18:15:22 666
定义接口
public interface Student {
void buy();
String talk();
}
实现类
public class Lisi implements Student {
@Override
public void buy() {
System.out.println("买");
}
@Override
public String talk() {
System.out.println("说");
return "说"
}
}
代理类 实现InvocationHandler
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MyInvocation implements InvocationHandler {
private Object obj;
public MyInvocation(Object obj) {
this.obj = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("talk")) {
System.out.println("增强方法");
method.invoke(obj, args);
return "说";
}
return method.invoke(obj, args);
}
}
测试
import java.lang.reflect.Proxy;
public class Test {
public static void main(String[] args) {
Lisi s=new Lisi();
MyInvocation my=new MyInvocation(s);
//参数一:Lisi类的类加载器
//参数二:Lisi实现的所有接口
//参数三:实现了invocationHandler接口的对象
Student lisi= (Student) Proxy.newProxyInstance(s.getClass().getClassLoader(), s.getClass().getInterfaces(), my);
lisi.buy();
System.out.println(lisi.talk());
}
}