簡體   English   中英

Java 中的匿名內部類有沒有辦法“丟失”他們的 scope?

[英]Is there a way for anonymous inner classes in Java to “lose” their scope?

當我將匿名內部 class 傳遞給 function 時,我可以在 scope 的方法中引用當前 scope 中的變量,如 ZCBB142F2ED29DCCAB21、so

class Caller {
    private Object callerPrivate;

    // ...

    public void someMethod() {
        final String callerLocal = "Eyes only";

        ISomeInterface anon = new ISomeInterface() {
                                     public void doSomethingInterfacy {
                                         System.out.println(callerPrivate.toString());
                                         System.out.println(callerLocal);
                                     }
                                  };
        // this is some other object that puts ISomeInterfaces in a queue
        // and makes them doSomethingInterfacy later
        myCallManager.enqueue(anon);
    }
}

現在,在上面的 someMethod 運行之后,調用者和帶有小匿名的隊列可以 go 分開,據我了解,JVM 使所有引用保持正確,因此這始終有效。

但是,例如,如果隊列被序列化,程序關閉並重新啟動,然后隊列被反序列化並且其中的項目應該運行,而 Caller 實例早已消失並被遺忘,該怎么辦?

還有其他方法可以讓周圍的 object 和匿名的內部 class 以一種在匿名 class 內部調用不再起作用的方式分開嗎?

不要序列化本地類,因為 (a) 文檔是這樣說的,並且 (b) 序列表示不穩定(它們一開始就沒有穩定的名稱)。

如果您不希望您的實例保留外部 this 和使用的最終局部變量的字段,請使用(靜態)嵌套 class 或外部 class。 對於 (Java) 序列化,您可以使用writeReplace序列化串行代理 object。

不要忘記您的匿名內部 class 包含隱式this引用。 即對周圍 class 的引用。

因此,如果您序列化您的內部 class,將會引用您的外部 class。 如果您使用XStream進行序列化並查看 XML output,您可以清楚地看到這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM