我有一個涉及多個類的 Java 11 項目。在當前場景中,我的 2 個類(A 和 B)實現了 java Finalize() 方法,該方法現已永久棄用。我知道該方法可能不會在不久的將來被刪除,但我認為最好立即找到 Finalize 的替代方法。A類中的finalize()主要關注于銷毀一個受保護的成員變量long類型的對象,并將某些消息打印到日志中。B 類中的 Finalize() 只是將某些消息打印到日志中。類 A 的實例是從其他幾個類創建的,類 B 擴展了另一個類 ClassLoader。(下面包含代碼片段。)我經歷了很多建議,例如,可通過 try-with-resources 自動關閉可清理的界面嘗試-捕獲-最終這些一開始就沒有得到很好的解釋,即使解釋得很好,這些示例也特定于單類項目,并且主方法存在于同一類中。我無法繼續使用我在網上找到的最小解決方案。經過我的研究,帶有 try-with-resources 的 Autocloseable 似乎是我的最佳選擇。我知道我的類 A 和 B 應該實現 Autocloseable,而被調用者(這里有點不確定)應該使用 try-with-resources。我將不勝感激任何有助于簡化這個問題的幫助,即使它是為了填補我對這個場景的理解中可能存在的空白。A.javaclass A{? ? protected long a_var;? ? protected A(String stmt, boolean isd)? ? {? ? ? ? // a_var is initialized here? ? }? ? public void finalize()? ? {? ? ? ? if(a_var != 0)? ? ? ? {? ? ? ? ? ? log("CALL destroy !");? ? ? ? ? ? destroy(a_var);? ? ? ? ? ? log("DONE destroy !");? ? ? ? }? ? }}B.javapublic class B extends extends ClassLoader{? ? protected void finalize ()? ? {? ? ? ? log("No action");? ? }}
1 回答

米琪卡哇伊
TA貢獻1998條經驗 獲得超6個贊
因此,帶有 try-with-resources 的 AutoCloseable 接口似乎是迄今為止最好的選擇。根據我的說法,finalize 的這種替代方案是最容易實現的 - 但這當然可能會根據每個項目的復雜性而有所不同。
類 A 必須實現 AutoCloseable class A implements AutoCloseable,并且創建其對象的所有位置都應包含在 try 中,例如 try (A obj = new A())
現在更進一步,重寫 AutoCloseable 提供的 close 方法,并從內部調用 destroy() 。
class A implements AutoCloseable
{
@Override
public void close()
{
//log messages
destroy();
}
}
class X
{
// suppose creating object of A within some method
// enclose in try
try ( A obj = new A ())
{
//use obj
}
// at the end of scope, the close() method of A will be called.
}
添加回答
舉報
0/150
提交
取消