实现类似内部 class 的引用行为?

Implement inner-class-like reference behaviour?

首先,请允许我解释一下我观察到的一个“行为”,然后我会在“示例”部分提问。

内部-class-参考行为

在 Java 中我们可以有(非静态的)inner-classes,这看起来像是对它们的强引用container-class and/or owner-class, 但不会导致内存泄漏.

我的意思是,我观察到即使 owner-class 和 inner-class 都保持对彼此的强引用,classes 无论如何都会被垃圾收集(一旦没有外部 class 引用它们,尽管有引用递归)。

In other words, or in other programming-languages, where "reference-counters" are often used (unlike Java?);

We could achieve such behaviour if owner-class and all inner-classes share the same reference-counter. Where just like above, even if we only keep a single reference to inner-class, owner-class is kept as well.

示例(背景和问题)

我之前使用上述行为的逻辑是这样的:

public class WebApi {
    public UserApi user = new UserApi();
    public PostApi post = new PostApi();

    protected String post(String url, String json) {
        // ...
    }

    public class UserApi {
        public void login() {
            WebApi.this.post(...);
        }

        public void logout() {
            WebApi.this.post(...);
        }

        // ...
    }

    public class PostApi {
        // ...
    }
}

然后项目一天一天地增长,直到每个 UserApiPostApi classes 都应该有自己的独立文件(而不是 inner-class一个大文件的 es)。

我们如何为外部 classes 实现上述“Inner-class-reference”行为?

In Java we can have (non-static) inner-classes, which seem to "behave" like having a strong-reference to their container-class and/or owner-class, but without causing memory-leak.

I mean, I observed that even if both owner-class and inner-class keep strong-reference to each other, the classes are garbage-collected anyway (once no external class references them, although having reference-recursion).

是的,这就是引用在 Java 中的工作方式:如果一个对象是可访问的,那么它会被保留,如果不是,那么它(最终)是 garbage-collected。

But how can we implement above described "Inner-class-reference" behaviour for external classes?

您不需要做任何特别的事情:只需给 UserApi 一个 WebApi 类型的字段,并在构造函数中初始化它。

Java 的 reference-tracing 和垃圾收集将确保,只要任何可访问的 UserApi 实例持有对给定 WebApi 实例的引用,WebApi 实例也被认为是可达的,因此被保留。