作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
当我使用 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.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/
据我所知,不能保证 Object.finalize() 总是被调用。但是如果有重要的非GC资源,并且用户没有意外调用close(),我该如何释放该资源?PS。 .NET中的Object.Finaliz
我是一名优秀的程序员,十分优秀!