package com.zhen.aop1;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class DynaProxy implements InvocationHandler {
/**
* 要处理的对象(也就是我们要在方法的前后加上业务逻辑的对象,如例子中的Hello)
*/
private Object delegate;
/**
* 动态生成方法被处理过后的对象 (写法固定)
*
* @param delegate
* @param proxy
* @return
*/
public Object bind(Object delegate) {
this.delegate = delegate;
return Proxy.newProxyInstance(
this.delegate.getClass().getClassLoader(), this.delegate
.getClass().getInterfaces(), this);
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null;
try {
// 执行原来的方法之前记录日志
Logger.logging(Level.DEBUGE, method.getName() + " Method end .");
// JVM通过这条语句执行原来的方法(反射机制)
result = method.invoke(this.delegate, args);
// 执行原来的方法之后记录日志
Logger.logging(Level.INFO, method.getName() + " Method Start!");
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class DynaProxy implements InvocationHandler {
/**
* 要处理的对象(也就是我们要在方法的前后加上业务逻辑的对象,如例子中的Hello)
*/
private Object delegate;
/**
* 动态生成方法被处理过后的对象 (写法固定)
*
* @param delegate
* @param proxy
* @return
*/
public Object bind(Object delegate) {
this.delegate = delegate;
return Proxy.newProxyInstance(
this.delegate.getClass().getClassLoader(), this.delegate
.getClass().getInterfaces(), this);
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null;
try {
// 执行原来的方法之前记录日志
Logger.logging(Level.DEBUGE, method.getName() + " Method end .");
// JVM通过这条语句执行原来的方法(反射机制)
result = method.invoke(this.delegate, args);
// 执行原来的方法之后记录日志
Logger.logging(Level.INFO, method.getName() + " Method Start!");
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}