我想在类的实例关闭或销毁时执行一两个操作。我正在寻找类似于 Activity 中的 onDestroy 的东西。
编辑
我已经添加了我的代码,其中指明了我如何从我的 Helper 类返回 SQLiteDatabase。我使用终结代码来确保数据库已关闭。
public class PMDBDatabase {
private static SQLiteDatabase DataBase = null;
private static PMDBHelper dbHelper = null;
public SQLiteDatabase getDatabase(Context ctx) throws SQLException {
if (DataBase == null) {
dbHelper = PMDBHelper.getInstance(ctx);
DBOpen();
} else
if(!DataBase.isOpen())
DBOpen();
return DataBase;
}
private void DBOpen() throws SQLException {
DataBase = dbHelper.getWritableDatabase();
}
public void close(){
if(DataBase != null) DataBase.close();
}
protected void finalize() throws Throwable {
try {
close();
} finally {
super.finalize();
}
}
}
能否请您帮助这位Java/Android编程新手并指出finalize的实现是否正确?
非常感谢您的宝贵时间,
让
最佳答案
你不能这样做,因为 GC
会自动处理它。
Because Java is a garbage collected language you cannot predict when (or even if) an object will be destroyed. Hence there is no direct equivalent of a destructor. There is an inherited method called finalize, but this is called entirely at the discretion of the garbage collector.
完成
It is possible to use something similar to a destructor in Java, the method Object.finalize() , which however does not work exactly like a standard destructor would.
关于java - 如何在简单的非 Activity java 类中创建类似于 onDestroy 的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32559282/