垃圾收集和反射

Chr*_*ett 7 java reflection garbage-collection memory-leaks

我想知道当你有一个带有反射的类来获取一些字段值时垃圾收集是如何工作的.JVM如何知道这些字段引用的值是可访问的,因此当正式语言语法不用于访问它们时,目前不符合垃圾收集的条件?

一个表示问题的小片段(尽管这里过分强调反思):

/**
 *
 */

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

干杯,
克里斯

Rob*_*bin 10

如果要访问实例的字段,则仍需要对该实例的引用.对于那种情况,GC没有任何异常.


Pet*_*rey 5

要访问对象的字段,您必须具有对该对象的引用.如果您通过反射或直接访问它,它对您是否有强烈的对象引用没有任何区别.