Chris Dennett
Chris Dennett

Reputation: 22721

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

Upvotes: 8

Views: 2773

Answers (3)

Trent Gray-Donald
Trent Gray-Donald

Reputation: 2346

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.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533530

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.

Upvotes: 5

Robin
Robin

Reputation: 24262

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.

Upvotes: 10

Related Questions