站内搜索: 请输入搜索关键词

当前页面: 开发资料首页Java 专题java动态代理的一点认识

java动态代理的一点认识

摘要: java动态代理的一点认识

</td> </tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="282" height="86" align="center" valign="top"> </td> <td width="402" valign="top">

1.首先实际的业务处理,由于采用动态代理(AOP思想)所以,必须基于接口编程.
package proxy;
public interface BusinessInterface {
public void processBusiness();
public int add(int a,int b);
}
2.实现具体业务的实现类
package proxy;
public class BusinessImpl implements BusinessInterface {
public void processBusiness() {
System.out.println("-----------processBusiness");
}
public int add(int a,int b)
{
System.out.println("result="+(a+b));
return a+b;
}
}

</td></tr> </table>


3.InvocationHandler接口提供一个执行处理器,然后通过java.lang.reflect.Proxy得到一个
代理对象,通过这个代理对象来执行商业
package proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.logging.Logger;

/**
* 日志代理处理器
* InvocationHandler接口提供了一个执行处理器
*/
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 o = null;
try {
logger.info("method stats..." + method);
o = method.invoke(delegate, args);
logger.info("method ends..." + method);
} catch (Exception e) {
logger.info("Exception happends...");
}
return o;
}
}
4.测试类
package proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class Test {
public static void main(String[] args) {
// 具体实现类
BusinessInterface businessImp = new BusinessImpl();
// 动态代理执行处理器
InvocationHandler handler = new LogHandler(businessImp);
// 代理对象
BusinessInterface proxy = (BusinessInterface) Proxy.newProxyInstance(
businessImp.getClass().getClassLoader(), businessImp.getClass()
.getInterfaces(), handler);
// 由代理对象来执行商业方法
// 在商业方法被调用的同时,执行处理器会被自动调用
proxy.processBusiness();
proxy.add(1, 2);
}
}

运行结果:


C:\java>java Test
2006-4-5 16:56:13 LogHandler invoke
信息: method stats...public abstract void BusinessInterface.processBusiness()
-----------processBusiness
2006-4-5 16:56:15 LogHandler invoke
信息: method ends...public abstract void BusinessInterface.processBusiness()
2006-4-5 16:56:15 LogHandler invoke
信息: method stats...public abstract int BusinessInterface.add(int,int)
result=3
2006-4-5 16:56:15 LogHandler invoke
信息: method ends...public abstract int BusinessInterface.add(int,int)

C:\java>


</td> </tr> <tr>


↑返回目录
前一篇: 一个AOP权限验证的小例子
后一篇: 对代理模式与Java动态代理类的理解