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

Java 第七天 动态代理

代理类需实现InvocationHandler接口:

public interface InvocationHandler
{
    public Object invoke(Object proxy,Method method,Object[] args) throws Throwable;
}

其中参数:

proxy - 在其上调用方法的代理实例
method - 对应于在代理实例上调用的接口方法的 Method 实例。Method 对象的声明类将是在其中声明方法的接口,该接口可以是代理类赖以继承方法的代理接口的超接口。
args - 包含传入代理实例上方法调用的参数值的对象数组,如果接口方法不使用参数,则为 null。

返回值是从代理实例的方法调用返回的值。

 

运行时代理对象的产生(一般转换为接口使用):
Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), invocationHandler)

target.getClass().getClassLoader() - 代理类的类加载器
target.getClass().getInterfaces() - 代理类要实现的接口列表
invocationHandler - 实现了InvocationHandler的类的实例(方法调用的调用处理程序)

调用接口所声明的代理对象的方法时即调用了实现InvocationHandler接口的类的invoke方法(InvocationHandler接口成员)

动态代理是Spring AOP实现的原理,常用于异常,日志,性能检测,权限,事务

示例代码:

//UserProxy.Java

package com.xpp.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class UserProxy implements InvocationHandler {

    private Object target;//被代理对象

    public Object bind(Object target) {
        this.target = target;

        return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        Object result = null;

        System.out.println(method.getName() + " call is starting");

        result = method.invoke(target, args);

        System.out.println(method.getName() + " call ended");
        return result;
    }
}
//Client.Java
package com.xpp.client;

import com.xpp.dao.UserDAO;
import com.xpp.dao.impl.UserDAOFileImpl;
import com.xpp.model.User;
import com.xpp.proxy.UserProxy;

public class Client {
    public static void main(String[] args) {
        UserProxy up = new UserProxy();
        UserDAO ud = (UserDAO) up.bind(new UserDAOFileImpl());
        ud.AddUser(new User());
    }
}

 

posted @ 2014-01-05 01:06  Peter_xpp  阅读(154)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3