静态代理和动态代理

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: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();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值