一、单独创建类
1.创建被代理类
public interface Iyao {
void eat(String s);
}
被代理类必须实现一个接口
public class yaoImpl implements Iyao {
@Override
public void eat(String s) {
System.out.println("hello"+s);
}
}
2.创建代理类,代理类要实现InvocatinHandler接口,重写invoke方法,传入被代理类的实例
public class MyProxy implements InvocationHandler {
private Iyao yao;
public MyProxy(Iyao yao) {
this.yao = yao;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object shabi = method.invoke(yao, args);
return shabi;
}
}
3.编写主方法
public class mian {
public static void main(String[] args) {
Iyao iyao=new yaoImpl();
InvocationHandler ihd=new MyProxy(iyao);
Iyao o =(Iyao) Proxy.newProxyInstance(ihd.getClass().getClassLoader(), iyao.getClass().getInterfaces(), ihd);
o.eat("world");
}
}
二、使用匿名内部类,不用再单独创建代理类
Iyao yao = new yaoImpl();
Iyao myproxy = (Iyao) Proxy.newProxyInstance(yao.getClass().getClassLoader(), yao.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object invoke = method.invoke(yao, args);
return invoke;
}
});
myproxy.eat("wsdfds");
输出结果:
也可以改变invoke参数增强代码:
Iyao yao = new yaoImpl();
Iyao myproxy = (Iyao) Proxy.newProxyInstance(yao.getClass().getClassLoader(), yao.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object invoke = method.invoke(yao, "增强");
return invoke;
}
});
myproxy.eat("wsdfds");
}
输出结果: