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,
Chris
If 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.