Business.class
package aop;
public interface Business {
public void print();
}
BusinessImpl.class
package aop;
import java.util.logging.Logger;
public class BusinessImpl implements Business {
private Logger logger = Logger.getLogger(this.getClass().getName());
public void print() {
// System.out.println("Doing...");
logger.info("Doing .....");
}
}
静态代理
StaticProxy .java
package invocation;
import java.util.logging.Logger;
/**
* @author E-mail:[email protected]
* @version 创建时间:2008-6-17 下午11:28:37 类说明
*/
public class StaticProxy {
private Logger logger = Logger.getLogger(this.getClass().getName());
public Business business;
public StaticProxy(Business business) {
this.business = business;
}
void print() {
logger.info("Start");
// 回调
business.print();
logger.info("End");
}
}
StaticProxyTest.java
package invocation;
/**
* @author E-mail:[email protected]
* @version 创建时间:2008-6-17 下午11:38:38
* 类说明
*/
public class StaticProxyTest {
public static void main(String[] args) {
Business business = new BusinessImpl();
StaticProxy proxy = new StaticProxy(business);
proxy.print();
}
}
动态代理
LogHandler.class
package aop;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.logging.Logger;
public class LogHandler implements InvocationHandler {
private Logger logger = Logger.getLogger(this.getClass().getName());
private Object delegate;
public LogHandler(Object delegate) {
this.delegate = delegate;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object object = null;
try {
logger.info("start" + method);
object = method.invoke(delegate, args);
logger.info("end" + method);
} catch(Exception e) {
logger.info("Exception");
}
return object;
}
}
Main.class
package aop;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class Main {
public static void main(String[] args) {
Business business = new BusinessImpl();
InvocationHandler handler = new LogHandler(business);
System.out.println(business.getClass().getInterfaces());
Business proxy = (Business) Proxy.newProxyInstance( business.getClass().getClassLoader(),
business.getClass().getInterfaces(), handler);
proxy.print();
}
}