Inner Class有一个对外部类的隐式引用,可能会泄漏内存

Jie*_*Jie 5 java static memory-leaks inner-classes

在了解了内部类之后,我理解它有一个对外部类的隐式引用.

但我的老师告诉我,最好的方法是不使用内部类,更喜欢使用静态内部类.因为内部类可能会泄漏内存.

有人可以解释一下吗?

Zie*_*elu 5

在您的评论的答案(如果我在评论中发布它将是不可读的),它所属的地方.访问外部内部类的示例.

public class Dog {
    String name;
}

public class HugeKennel {
    Double[] memmoryWaste = new Double[10000000];


    public List<Dog> getDogs() {
        SneakyDog trouble = new SneakyDog("trouble");
        return Arrays.asList(trouble);
    }

    class SneakyDog extends Dog {
        SneakyDog(String name) {
            this.name = name;
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

你代码中的其他地方

List<Dog> getCityDogs() {
    List<Dog> dogs = new ArrayList<>();
    HugeKennel k1 = ...
    dogs.addAll(k1.getDogs());
    HugeKennel k2 = ...
    dogs.addAll(k2.getDogs());
    return dogs;
}

....

List<Dog> cityDogs = getCityDogs();
for (Dog dog: dogs) {
    walkTheDog(dog);
}
// even though the Kenels were local variables in of getCityDogs(), they cannot be removed from the memory, as the SneakyDogs in the list are still referencing their parent kennels.
//from now on, until all the dogs are not disposed off, the kennels also have to stay in the memory.
Run Code Online (Sandbox Code Playgroud)

因此,您不需要通过其parrent类访问内部类,一旦创建了内部对象,它就可以用作任何其他对象,并且可以"泄漏"到其容器类之外,就像上面的示例中那样,当狗列表将引用狗,但每只狗仍然会"知道"它的狗窝.

StackTrace中的链接示例与典型用例相关,当内部类被创建为"ad hock"作为匿名内部类时,但它是同样的问题.如果将引用传递给内部类的任何实例,那么您也"传递"对外部类的引用.