• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

老王的蜕变

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

java 简单的动态代理例子

package util;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.lang.reflect.Method;
//抽象角色:java动态代理的实现目前只支持接口,不支持抽象类
interface BusinessFoo
{
    void foo();
}
interface BusinessBar
{
   String bar(String message);
}
//真实角色:真正实现业务逻辑方法
class BusinessFooImpl implements BusinessFoo
{
   public void foo()
   {
       System.out.println("BusinessFooImpl.foo()");
   }
}
class BusinessBarImpl implements BusinessBar
{
   public String bar(String message)
   {
       System.out.println("BusinessBarImpl.bar()");
       return message;
   }
}
//动态角色:动态生成代理类
class BusinessImplProxy implements InvocationHandler
{
   private Object obj;
   BusinessImplProxy() {
   }
   BusinessImplProxy(Object obj) {
       this.obj = obj;
   }
   public Object invoke(Object proxy,Method method,Object[] args) throws Throwable
   {
       Object result = null;
       doBefore();
       result = method.invoke(obj,args);
       doAfter();
       return result;
   }
   public void doBefore(){
       System.out.println("do something before Business Logic");
   }
   public void doAfter(){
       System.out.println("do something after Business Logic");
   }
   public static Object factory(Object obj)
   {
       Class cls = obj.getClass();
       return Proxy.newProxyInstance(cls.getClassLoader(),cls.getInterfaces(),new BusinessImplProxy(obj));
   }
}
//测试类
public class DynamicProxy
{    
   public static void main(String[] args) throws Throwable
   {
       BusinessFooImpl bfoo = new BusinessFooImpl();
       BusinessFoo bf = (BusinessFoo)BusinessImplProxy.factory(bfoo);
       bf.foo();
       System.out.println();
       
       BusinessBarImpl bbar = new BusinessBarImpl();
       BusinessBar bb = (BusinessBar)BusinessImplProxy.factory(bbar);
       String message = bb.bar("Hello,World");
       System.out.println(message);
   }
}
 

  

posted on 2013-04-18 15:13  老王的蜕变  阅读(178)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3