我正在与Java中的垃圾收集器作斗争。我想列出所有可从三个列表中的某个对象访问的对象,具体取决于引用类型:strong, soft, weak
。那里没有幽灵。我知道我需要通过递归和反射来做,但我找不到一种简单的方法来实现它。请你帮助我好吗?这不是一个非常困难的问题,但我不知道如何以一种简单而正确的方式实现它。注意我不是要检测内存泄漏。
public static List < Object > getStronglyReachable (Object from)
// contains all objects that are ONLY strongly reachable
public static List < Object > getSoftlyReachable (Object from)
// contains all objects that are strongly OR softly reachable
public static List < Object > getWeaklyReachable (Object from)
// contains all objects that are strongly OR softly OR weakly reachable
这是我目前所拥有的,但它并没有真正起作用:
private static void collectAllReachableObjects (Object from, Set < Object > result) throws IllegalArgumentException, IllegalAccessException
{
// if it's already added, don't do that again
if (result.contains (from))
return;
// isStrongReference makes softAllowed false and weakAllowed false;
// isSoftReference makes softAllowed true and weakAllowed false;
// isWeakReference makes softAllowed true and weakAllowed true;
// Phantom References are never allowed
if (PhantomReference.class.isAssignableFrom (from.getClass ())) return;
if (weakAllowed == false && WeakReference.class.isAssignableFrom (from.getClass ())) return;
if (softAllowed == false && SoftReference.class.isAssignableFrom (from.getClass ())) return;
// add to my list
result.add (from);
// if an object is an array, iterate over its elements
if (from.getClass ().isArray ())
for (int i = 0; i < Array.getLength (from); i++)
collectAllReachableObjects (Array.get (from, i), result);
Class < ? > c = from.getClass ();
while (c != null)
{
Field fields[] = c.getDeclaredFields ();
for (Field field : fields)
{
boolean wasAccessible = field.isAccessible ();
field.setAccessible (true);
Object value = field.get (from);
if (value != null)
{
collectAllReachableObjects (value, result);
}
field.setAccessible (wasAccessible);
}
c = c.getSuperclass ();
}
}