public interface SayHelloService {
void sayHello(String name);
}
class SayHellowServiceImpl implements SayHelloService {
@Override
public void sayHello(String name) {
System.out.println("hello" + name);
}
}
class Invocation{
Object target = null;
Method method = null;
Object[] args = null;
public Invocation(Object target, Method method,Object[] args){
this.args = args;
this.method = method;
this.target =target;
}
Object proceed() throws Exception{
return method.invoke(target,args);
}
}
interface Interceptor {
boolean before();
void around(Invocation invocation) throws Exception;
void after();
void throwException();
void keepRunning();
}
class MyInterceptor implements Interceptor{
@Override
public boolean before() {
System.out.println("before执行了");
return true;
}
@Override
public void around(Invocation invocation) throws Exception{
System.out.println("around准备执行了");
invocation.proceed();
System.out.println("around执行结束了");
}
@Override
public void after() {
System.out.println("after执行了");
}
@Override
public void throwException() {
System.out.println("throwException执行了");
}
@Override
public void keepRunning() {
System.out.println("keepRunning执行了");
}
}
class ProxyBean implements InvocationHandler{
Object target = null;
Interceptor interceptor = null;
static Object getProxyBean(Object target, Interceptor interceptor){
ProxyBean proxyBean = new ProxyBean();
proxyBean.interceptor = interceptor;
proxyBean.target = target;
return Proxy.newProxyInstance(target.getClass().getClassLoader()
, target.getClass().getInterfaces(),proxyBean);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
boolean before = interceptor.before();
boolean findExceotion = false;
try{
if(before){
Invocation invocation = new Invocation(target,method,args);
interceptor.around(invocation);
}else{
method.invoke(target,args);
}
}catch (Exception e){
findExceotion = true;
e.printStackTrace();
}
interceptor.after();
if(findExceotion){
interceptor.throwException();
}else{
interceptor.keepRunning();
}
return null;
}
public static void main(String[] args) {
SayHellowServiceImpl sayHellowService = new SayHellowServiceImpl();
SayHelloService proxyBean = (SayHelloService) ProxyBean
.getProxyBean(sayHellowService, new MyInterceptor());
proxyBean.sayHello("world");
}
}