Garbage collection and reflection

I am wondering how garbage collection works when you have a reflection class used to get field values. How does the JVM know that references to values ​​in these fields are accessible and therefore not suitable for garbage collection at the moment when the formal language syntax is not used to access them?

A small snippet indicating a problem (although the reflection here was excessive):

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

Greetings
Chris

+7
source share
3 answers

If you access the fields of an instance, you still need a reference to that instance. In this case, there would be nothing abnormal with respect to the GC.

+10
source

To access the field of an object, you must have a link to this object. If you access it using reflections or directly, it doesn't matter if you have a strong reference to the object.

+5
source

This is a slightly strange test case: you use reflection to access "this". By definition, "this" is alive when used in an instance method of the declaration class, so there will be no GCed.

But what's more, reflection just allows you to manipulate fields, etc. in objects to which you already have links. What is the key - if you can give the Flip instance for validation, you obviously still have a reference to the object, so it remains alive.

+1
source

All Articles