简体   繁体   English

finalize() 方法

[英]finalize() method

I want to know why its neccessary to write this statement super.finalize() in the following我想知道为什么必须在下面写这个语句 super.finalize()

code.代码。

protected void finalize() throws Throwable {

    try {

        close();

    } catch(Exception e) {

    }

    finally {

        super.finalize();


    }
}

You're overriding the finalize method and since you're doing this, you need to call the parents finalize method as well.您正在覆盖 finalize 方法,并且由于您正在这样做,因此您还需要调用父母的finalize方法。 Otherwise it's possible that it didn't close streams or other resources accordingly.否则,它可能没有相应地关闭流或其他资源。

You don't have to call the object's finalize() method for sure, but it can produce really nasty bugs when you eg copy/paste code to another class or change the parent of the inheritance.您不必确定调用对象的finalize()方法,但是当您将代码复制/粘贴到另一个 class 或更改 inheritance 的父级时,它会产生非常讨厌的错误。

It is wrapped in the finally-block to make sure that it is always called, no matter what happens (eg an exception in the close() method).它被包装在 finally 块中以确保它总是被调用,无论发生什么(例如 close() 方法中的异常)。

You should also take a look at the Javadoc: http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#finalize您还应该查看 Javadoc: http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#finalize

If close() throws an exception, then the superclass's finalizer would never be called without the finally clause.如果close()抛出异常,那么如果没有finally子句,就永远不会调用超类的终结器。 Although, if the superclass is just an Object then it really doesn't matter: according to docs, The finalize method of class Object performs no special action;虽然,如果超类只是一个Object那么它真的没关系:根据文档, class Object 的 finalize 方法不执行任何特殊操作; it simply returns normally .它只是正常返回

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM