JDK自带的动态代理Proxy类和InvocationHandler接口
来源:互联网 发布:sql server oracle 编辑:程序博客网 时间:2024/05/01 22:22
JDK自带的动态代理主要是指,实现了InvocationHandler接口的代理类,实现了InvocationHandler接口的类,会继承一个invoke方法,通过在这个方法中添加某些代码,从而完成在方法前后添加一些动态的东西。JDK自带的动态代理依赖于接口,如果有些类没有接口,则不能实现动态代理。
下面是具体的例子:
首先是接口:
package yq.com;
public interface StudentDao {
public void saveStudent();
}
然后是接口的实现类:
package yq.com.impl;
import yq.com.StudentDao;
public class StudentDaoImpl implements StudentDao {
/**
* {@inheritDoc}.
*/
@Override
public void saveStudent() {
System.out.println("保存学生成功!");
}
}
然后是动态代理类:
package yq.com.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class DaoProxy implements InvocationHandler {
private Object originalObject;
public Object bind(Object obj) {
this.originalObject = obj;
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);
}
public void preMethod() {
System.out.println("------执行方法之前--------");
}
public void afterMethod() {
System.out.println("------执行方法之后--------");
}
/**
* {@inheritDoc}.
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
preMethod();
result = method.invoke(this.originalObject, args);
afterMethod();
return result;
}
}
最后是测试类:(注意TestCase是junit中的东西,请引入junit包)
public class TestProxy extends TestCase {
public void testDaoProxy() {
StudentDao sDao = new StudentDaoImpl();
DaoProxy proxy = new DaoProxy();
sDao = (StudentDao) proxy.bind(sDao);
sDao.saveStudent();
}
}
- JDK自带的动态代理Proxy类和InvocationHandler接口
- 【引用】模拟JDK实现动态代理(自写Proxy类和InvocationHandler接口)
- JDK动态代理proxy,InvocationHandler
- 动态代理两个类Proxy和InvocationHandler的模拟实现
- jdk proxy invocationhandler (jdk动态代理)
- JDK使用InvocationHandler和Proxy实现动态代理
- Dynamic Proxy(JDK自带的动态代理实现)
- JDK的动态代理深入解析(Proxy,InvocationHandler)
- JDK的动态代理深入解析(Proxy,InvocationHandler)
- JDK的动态代理深入解析(Proxy,InvocationHandler)
- JDK的动态代理深入解析(Proxy,InvocationHandler)
- jdk的动态代理 proxy invocationHandler 面试重要!!
- JDK的动态代理深入解析(Proxy,InvocationHandler)
- JDK的动态代理深入解析(Proxy,InvocationHandler)
- JDK的动态代理深入解析(Proxy,InvocationHandler)
- JDK的动态代理深入解析(Proxy,InvocationHandler)
- JAVA JDK 动态代理 proxy invocationHandler
- cglib动态代理和JDK InvocationHandler动态代理的比较
- Android自定义View的实现方法,带你一步步深入了解View(四)
- 群策CRM全网版,打通全网“一站式”盈利
- MVC 数据分析系统
- WIN7 IIS7.5web部署.NET项目遇到的问题
- J2EE是什么(二)
- JDK自带的动态代理Proxy类和InvocationHandler接口
- 冒泡算法 SAS & Python
- 微软100题(83)百度面试题_memmove实现
- TFS开源思考
- 摄像头记录
- 黑马程序员_反射
- IOS程序发布AppStore流程
- 玩玩PCtoLCD,得到指定大小字模库
- php中new对象加括号和不加括号的区别