Garbage collection and reflection
I'm wondering how garbage collection works when you have a class with reflection used to get some field values. How is the JVM aware that the values references by these fields are accessible and so not eligible for garbage collection at the present moment, when formal language syntax is not used to access them?
A small snippet indicating the issue (although reflection has been over-emphasised here):
/**
*
*/
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);
}
}
}
Cheers,
ChrisIf you are accessing the fields of an instance, then you will still need a reference to that instance. There would be nothing abnormal about GC for that case.
To access a field of an object you must have a reference to that object. If you access it via reflections or directly it doesn't make any difference to whether you have a strong reference to the object.
It's a bit of an odd test case: you're using reflection to access "this". By definition, "this" is live when used in an instance method of the declaring class, so won't be GCed.
But more to the point, reflection simply allows you to manipulate fields, etc.. in objects to which you already have references. That's the key - ff you can give Reflect the instance to examine, you clearly still have a reference to the object, thus it stays alive.
精彩评论