java.lang.reflect.Proxy实例是否专门用于最终化处理?

时间:2013-01-06 16:38:21

标签: java reflection proxy

当我使用java.lang.reflect.Proxy.newInstance(...)创建接口实例时,对该对象的finalize的调用不会传递给invocationHandler。有人能指出我记录这种行为的地方吗?

private Method lastInvokedMethod = null;

@Test
public void finalize_methods_seem_to_disappear_on_proxies() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    final Method lengthMethod = CharSequence.class.getDeclaredMethod("length");
    final Method finalizeMethod = Object.class.getDeclaredMethod("finalize");
    final Method equalsMethod = Object.class.getDeclaredMethod("equals", new Class[] {Object.class});

    InvocationHandler handler = new InvocationHandler() {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            lastInvokedMethod = method;
            if (method.equals(lengthMethod))
                return 42;
            else if (method.equals(equalsMethod))
                return true;
            else
                return null;
        }
    };
    CharSequence proxy = (CharSequence) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class<?>[]{CharSequence.class}, handler);

    // check that invocationHandler is working via reflection
    lastInvokedMethod = null;
    assertEquals(42, invokeMethod(proxy, lengthMethod));
    assertEquals(lengthMethod, lastInvokedMethod);

    // check that other methods defined on Object are delegated
    lastInvokedMethod = null;
    assertEquals(true, invokeMethod(proxy, equalsMethod, "banana"));
    assertEquals(equalsMethod, lastInvokedMethod);

    // check that we can invoke finalize through reflection
    Object finalizableObject = new Object() {
        protected void finalize() throws Throwable {
            lastInvokedMethod = finalizeMethod;
            super.finalize();
        }
    };
    lastInvokedMethod = null;
    invokeMethod(finalizableObject, finalizeMethod);
    assertEquals(finalizeMethod, lastInvokedMethod);

    // Finally - a call to finalize is not delegated
    lastInvokedMethod = null;
    invokeMethod(proxy, finalizeMethod);
    assertNull(lastInvokedMethod);
}

private Object invokeMethod(Object object, Method method, Object... args) throws IllegalAccessException, InvocationTargetException {
    method.setAccessible(true);
    return method.invoke(object, args);
}

1 个答案:

答案 0 :(得分:8)

java.lang.reflect.Proxy API

•在代理实例上的java.lang.Object中声明的hashCode,equals或toString方法的调用将被编码并调度到调用处理程序的invoke方法,其方式与对接口方法调用进行编码和分派的方式相同,如上所述。传递给invoke的Method对象的声明类将是java.lang.Object。 从java.lang.Object继承的代理实例的其他公共方法不会被代理类覆盖,因此这些方法的调用与它们对java.lang.Object 的实例的行为相同。