java动态代理

来源:互联网 发布:苹果手机关闭数据流量 编辑:程序博客网 时间:2024/05/22 15:29

1)接口定义

 

public interface SubjectInf {
 public void say() ;
}

 

2)实现类,也是被代理的目标类

 

public class RealSubject implements SubjectInf{

 public void say() {
  System.out.println("该方法被正确调用...");
 }

}

 

3)代理实现

 

public class ProxyBean implements InvocationHandler {

 private SubjectInf inf ; // 定义被代理类的一个实例,必须存在; 
 //若不存在,测试结果显示toString()方法被无误调用,但输出首个ProxyTarget时抛出NullPointerException异常
 
 //结果显示,无论是以下哪种方法生成被代理类的一个实例,say()方法均被正常代理
 public ProxyBean(){
  inf = new RealSubject() ;
 }
 //推荐采用此种构造方法
 public ProxyBean(SubjectInf inf){
  this.inf = inf ;
 }
 
 public Object invoke(Object obj, Method method, Object[] args)
   throws Throwable {

  System.out.println("-----------------------------"); // 验证该方法是否正确调用
//  System.out.println("Object:" + obj); //运行异常,无法获取值,且从上面开始反复执行,直至栈溢出(StackOverflowError)
  System.out.println("Object:" + obj.getClass());  // Object:class $Proxy0

  System.out.println("Method:" + method);  //Method:public java.lang.String java.lang.Object.toString()

  System.out.println("Object[]:" + args);  // null,表明此时无参
  return method.invoke(inf, args);
 }

 public static void main(String[] args) {
  SubjectInf inf = new RealSubject();
  Object obj = Proxy.newProxyInstance(
    inf.getClass().getClassLoader(),    //调用该类的类加载器
    inf.getClass().getInterfaces(),  //调用该类所引用的接口
    new ProxyBean(inf)  //InvocationHandler对象
    );  

  System.out.println("ProxyTarget:"+obj);  // ProxyTarget:invoke_test.RealSubject@7c6768
  System.out.println("ProxyTarget:"+obj.getClass());  // ProxyTarget:class $Proxy0
  
  SubjectInf demo = (SubjectInf)obj ;    //此处只能是SubjectInf,否则抛出ClassCastException:异常
  demo.say() ; //  该方法被正确调用...
 }
}

 

原创粉丝点击