1、定义一个接口
interface Hello{
void sayHello();
}
2、定义被代理的类实现接口
class HelloA implements Hello{
@Override
public void sayHello() {
System.out.println("hello");
}
}
3、定义代理类并实现接口
class MyProxy implements InvocationHandler{
private HelloA helloA;//被代理类实例
public MyProxy(HelloA helloA) {
this.helloA=helloA;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if("sayHello".equals(method.getName())){
System.out.println("权限校验================");
}
return method.invoke(helloA,args); //调用被代理实例的方法
}
}
4、动态代理demo
public static void main(String[] args) {
HelloA helloA=new HelloA();
MyProxy myProxy=new MyProxy(helloA);
Hello proxy = (Hello) Proxy.newProxyInstance(myProxy.getClass().getClassLoader(), helloA.getClass().getInterfaces(), myProxy);
proxy.sayHello();
System.out.println();
}