Proxy.newProxyInstance()返回的只能是接口,即代理对象所实现的接口- package demo.proxy;
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
- import java.util.ArrayList;
- import java.util.List;
- public class ProxyOfArrayListDemo {
- /**
- * 23、 写一个 ArrayList 类的代理,实现和 ArrayList 类中完全相同的功能,
- * 并可以计算 每个方法运行的时间。
- */
- public static void main(String[] args) {
- ArrayList<String> al = new ArrayList<String>();
- List proxy = (List)Proxy.newProxyInstance(al.getClass().getClassLoader(),
- al.getClass().getInterfaces(),new MyInvocationHandler1(al));
- proxy.add("Hello java");
- proxy.remove(0);
- }
- }
- class MyInvocationHandler1 implements InvocationHandler{
- private Object obj;
-
- public MyInvocationHandler1(Object obj) {
- super();
- this.obj = obj;
- }
- @Override
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- Long l1 = System.currentTimeMillis();
- System.out.println("size of args : "+args.length +"..args[0] = "+args[0]);
- System.out.println("method : "+method);
- System.out.println("obj = "+obj);
- Object result = method.invoke(obj, args);
- System.out.println("result = "+result);
- Long l2 = System.currentTimeMillis();
- System.out.println(l2-l1);
- return result;
- }
-
- }
复制代码- size of args : 1..args[0] = Hello java
- method : public abstract boolean java.util.List.add(java.lang.Object)
- obj = []
- result = true
- 1
- size of args : 1..args[0] = 0
- method : public abstract java.lang.Object java.util.List.remove(int)
- obj = [Hello java]
- result = Hello java
- 0
复制代码
|
|