我想知道当您有一个使用反射来获取某些字段值的类时,垃圾回收是如何工作的。当不使用正式语言语法访问它们时,JVM 如何知道这些字段引用的值是可访问的,因此目前不符合垃圾回收条件?
指出问题的一小段(尽管此处过分强调了反射(reflection)):
/**
*
*/
import java.lang.reflect.Field;
public class B {
protected B previous = null, next = null;
/**
*
*/
public B(B from) {
this.previous = from;
}
public void transition(B to) {
this.next = to;
}
public B next() {
try {
Field f = getClass().getField("next");
f.setAccessible(true);
try {
return (B)f.get(this);
} finally {
f.setAccessible(false);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public B previous() {
try {
Field f = getClass().getField("previous");
f.setAccessible(true);
try {
return (B)f.get(this);
} finally {
f.setAccessible(false);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
干杯,
克里斯
最佳答案
如果您正在访问实例的字段,那么您仍然需要对该实例的引用。对于这种情况,GC 不会有任何异常。
关于java - 垃圾收集和反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6443972/