//针对Hello的静态代理
public class StaticProxy {
private final Hello hello;
public StaticProxy(Hello hello) {
this.hello = hello;
}
//代理Hello实例化对象的hello方法
public void hello() {
System.out.println("Before Method");
hello.hello();
System.out.println("After Method");
}
}
public interface Hello {
void hello();
}
Hello hello = () -> System.out.println("hello Method");
public class AroundProxy implements InvocationHandler {
private final Object obj;
public AroundProxy(Object obj) {
this.obj = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//做AOP切面
System.out.println("Before Method");
Object o = method.invoke(obj, args);
System.out.println("After Method");
return o;
}
}
Hello hello = () -> System.out.println("hello Method");
//进行代理
AroundProxy proxy = new AroundProxy(hello);
//获取代理得到的通用接口
Hello o = (Hello) Proxy.newProxyInstance(Hello.class.getClassLoader(), new Class[]{Hello.class}, proxy);
//好奇,输出了o的类型
System.out.println(o.getClass());
//使用接口
o.hello();
class com.sun.proxy.$Proxy0
Before Method
hello Method
After Method