java动态代理详解
2015-08-28 09:59
525 查看
代理模式示例代码:
动态代理的实现类:
public interface Subject { public void doSomething(); } public class RealSubject implements Subject { public void doSomething() { System.out.println( "call doSomething()" ); } } public class ProxyHandler implements InvocationHandler { private Object proxied; public ProxyHandler( Object proxied ) { this.proxied = proxied; } public Object invoke( Object proxy, Method method, Object[] args ) throws Throwable { //在转调具体目标对象之前,可以执行一些功能处理 //转调具体目标对象的方法 return method.invoke( proxied, args); //在转调具体目标对象之后,可以执行一些功能处理 } }
动态代理的实现类:
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import sun.misc.ProxyGenerator; import java.io.*; public class DynamicProxy { public static void main( String args[] ) { RealSubject real = new RealSubject(); Subject proxySubject = (Subject)Proxy.newProxyInstance(Subject.class.getClassLoader(), new Class[]{Subject.class}, new ProxyHandler(real)); proxySubject.doSomething(); //write proxySubject class binary data to file createProxyClassFile(); } public static void createProxyClassFile() { String name = "ProxySubject"; byte[] data = ProxyGenerator.generateProxyClass( name, new Class[] { Subject.class } ); try { FileOutputStream out = new FileOutputStream( name + ".class" ); out.write( data ); out.close(); } catch( Exception e ) { e.printStackTrace(); } } }
相关文章推荐
- Apriori算法的java实现
- Java线程
- maven 工程 dubbo服务的xml配置文件报错的问题
- java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, ho
- javamail发送邮件的简单实例
- 算法研究之合并两个已排序的数组java版
- Struts2拦截器配置
- Struts – Wildcards example
- Struts – Multiple configuration files example
- Java类中的具体集合
- Java之 出入门卫管理系统(一)
- Spring 使用注解方式进行事务管理
- ubuntu 编译 openjdk - open jdk
- Configure a welcome page in Struts
- JAVA中int、String的类型转换
- Java集合框架
- Configure the Struts Tag Libraries
- Eclipse WindowBuilder插件在线安装
- springmvc教程
- Struts Hello World Example