2008-01-24
静态代理和动态代理
Business.class
BusinessImpl.class
静态代理
StaticProxy .java
StaticProxyTest.java
动态代理
LogHandler.class
Main.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:congpeixue@126.com
* @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:congpeixue@126.com
* @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();
}
}
发表评论
- 浏览: 5094 次
- 性别:

- 来自: 杭州

- 详细资料
搜索本博客
最近加入圈子
最新评论
-
java回调
修正过了。 Printer 拥有一个参数为ICallBack类型的方法setC ...
-- by congpeixue -
Eclipse 类自动生成作者 ...
。
-- by congpeixue -
Eclipse 类自动生成作者 ...
不错。谢了!
-- by luckaway -
java回调
PrintHandler 拥有一个参数为ICallBack的方法setCallB ...
-- by ganqing1234 -
spring+webwork+ibatis
支持下,兄弟也不把lib放进去,害我一个个找,看到留言,望把数据库脚本也给传个, ...
-- by heshucha






评论排行榜