posts - 51, comments - 17, trackbacks - 0, articles - 9
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

java模式之动态代理

Posted on 2007-01-05 20:47 chenweicai 阅读(390) 评论(1)  编辑  收藏

package proxy;
/**
 *
 * @author chen
 *
 */
public interface Subject {
 abstract public void request();
 abstract public void request2();
}


package proxy;

/**
 *
 * @author chen
 *
 */
public class RealSubject implements Subject {
 
 public RealSubject(){
 }

 public void request() {
  // TODO Auto-generated method stub
  System.out.println("From real subject.request().");
 }
 
 public void request2() {
  // TODO Auto-generated method stub
  System.out.println("From real subject.request2()");
 }
}

package proxy;


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

/**
 *
 * @author chenweicai
 *
 */
public class DynamicSubject implements InvocationHandler {
 
 private Object sub;
 
 public DynamicSubject(){
 }
 
 public DynamicSubject(Object obj){
  this.sub = obj;
 }

 public Object invoke(Object proxy, Method method, Object[] args)
   throws Throwable {
  // TODO Auto-generated method stub
     System.out.println("before calling " + method);
     method.invoke(sub,args);
     System.out.println("after calling " + method);
  return null;
 }

}


package proxy;

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

/**
 *
 * @author chen
 *
 */
public class Client {
 static public void main(String[] args)
        throws Throwable{
    RealSubject rs = new RealSubject();  //在这里指定被代理类
    InvocationHandler ds = new DynamicSubject(rs);  //初始化代理类
    Class cls = rs.getClass();
  
    //以下是分解步骤
    /*Class c = Proxy.getProxyClass(cls.getClassLoader(),cls.getInterfaces()) ;
    Constructor ct=c.getConstructor(new Class[]{InvocationHandler.class});
    Subject subject =(Subject) ct.newInstance(new Object[]{ds});*/
  
    //以下是一次性生成
    Subject subject = (Subject) Proxy.newProxyInstance(cls.getClassLoader(),
    cls.getInterfaces(),ds );

    subject.request2();
   }
}


评论

# re: java模式之动态代理  回复  更多评论   

2007-01-05 22:50 by xzcqwer
这是在讲述springframework中ProxyFactoryBean的实现机理吧,呵呵

只有注册用户登录后才能发表评论。


网站导航: