gpt4 book ai didi

java - java.lang.reflect.Proxy 实例是否经过特殊处理以进行终结?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:13:02 25 4
gpt4 key购买 nike

当我使用 java.lang.reflect.Proxy.newInstance(...) 创建接口(interface)实例时,未传递对该对象的 finalize 调用到调用处理程序。任何人都可以指出记录此行为的位置吗?

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);
}

最佳答案

java.lang.reflect.Proxy API

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

关于java - java.lang.reflect.Proxy 实例是否经过特殊处理以进行终结?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14184248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com