java动态代理的基础问题


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.Vector;

public class VectorProxy implements InvocationHandler {
    private Object proxyObj;

    public VectorProxy(Object obj) {
        proxyObj = obj;
    }


    public Object invoke(Object obj, Method method, Object[] args) throws Throwable {
        System.out.println("Before calling : " + method);
        if (args != null) {
            for (Object o : args) {
                System.out.println(o);
            }
        }

        Object object = method.invoke(proxyObj, args);

        System.out.println("After calling : " + method);

        return object;
    }

    public static Object factory(Object obj) {
        Class<?> classType = obj.getClass();

        return Proxy.newProxyInstance(classType.getClassLoader(), obj.getClass().getInterfaces(), new VectorProxy(obj));
    }

    public static void main(String[] args) {
        List list = (List) factory(new Vector());

        list.add("hello");
    }
}

public Object invoke      这个方法的返回值能决定什么?为什么改成null就不对了

这个方法返回的是你执行的那个method方法的返回值。

这句话是以proxyObj,也即是你的代理对象作为主调,来执行method()方法,自然是返回method()的返回值了。
Object object = method.invoke(proxyObj, args);