5

我有一个涉及多个类的 Java 11 项目。在当前场景中,我的 2 个类 - A 和 B - 实现了 java finalize() 方法,该方法现在已被永久弃用。我知道该方法在不久的将来可能不会被删除,但我认为最好立即找到一个替代方法来完成。

A 类中的 finalize() 主要专注于销毁作为受保护成员变量的 long 类型的对象,并将某些消息打印到日志中。B 类中的 finalize() 只是将某些消息打印到日志中。

A 类的实例是从其他几个类创建的,B 类扩展了另一个类 ClassLoader。(下面包含代码片段。)

我经历了很多建议,例如,

这些首先解释得不是很好,即使它们解释得很好,这些示例也特定于单个类项目,其中 main 方法存在于同一类中。我无法继续使用我在网上找到的最小解决方案。

发表我的研究,Autocloseable with try-with-resources 似乎是我最好的选择。我知道我的 A 类和 B 类应该实现 Autocloseable,而被调用者(这里有点不确定)应该使用 try-with-resources。

我将感谢任何有助于简化此问题的帮助,即使它是为了填补我对场景的理解中可能存在的空白。

爪哇

class 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.java

public class B extends extends ClassLoader
{
    protected void finalize ()
    {
        log("No action");
    }
}
4

1 回答 1

2

因此,到目前为止,带有 try-with-resources 的 AutoCloseable 接口似乎是您的最佳选择。在我看来,这种 finalize 的替代方案是最容易实现的——但这当然可能会根据每个项目的复杂性而有所不同。

类 A 必须实现 AutoCloseableclass 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.
}
于 2019-09-24T08:44:17.513 回答