www.zhblog.net

Java 代理

实例

package com.corejava.base;





import java.lang.reflect.InvocationHandler;

import java.lang.reflect.Method;





public class TraceHandler implements InvocationHandler {

    private Object target;





    public TraceHandler(Object target) {

        this.target = target;

    }





    @Override

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        System.out.println(method.getName());

        return method.invoke(target, args);

    }

}


package com.corejava.base;





import java.lang.reflect.InvocationHandler;

import java.lang.reflect.Proxy;

import java.util.Arrays;

import java.util.Random;





public class ProxyComparable {





    public static void main(String[] args) {

        Object[] elements = new Object[10];

        for (int i = 0; i < elements.length; i++) {

            Integer value = i + 1;

            InvocationHandler handler = new TraceHandler(value);

            Object proxy = Proxy.newProxyInstance(null, new Class[]{Comparable.class}, handler);

            elements[i] = proxy;

        }





        Integer key = new Random().nextInt(elements.length) + 1;

        int result = Arrays.binarySearch(elements, key);

        if (result >= 0) {

            System.out.println(elements[result] instanceof Comparable);

            System.out.println(elements[result].toString());

        }

    }

}


Compareable 接口中的所有方法,其实现类的 handler 都会被调用。

接口就表明了哪些方法将被监听。


 

展开阅读全文

评论

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 心情