Java finalize() 在对象回收之前执行某项操作

如果在一个对象被回收之前要进行某些操作,该如何?

在Object类中有个finalize()方法,方法定义如下:

protect void finalize() throws Throwable

一个类只要覆写此方法即可在释放对象之前进行某些操作。

package com.gzu.eleven.forth.two;


/**
 * @author RayFuck Aug 5, 2016 11:33:31 AM
 */
public class Test {

    private String test1;

    private String test2;

    public Test(String test1, String test2) {
	this.test1 = test1;
	this.test2 = test2;
    }
    
    public String toString() {
	return "test1: " + test1 + ", test2: " + test2;
    }
    // 在释放资源前调用此方法。
    public void finalize() throws Throwable {
	System.out.println("The object is to release: " + this);
    }
    
    public static void main(String[] args) {
	Test test = new Test("qwer", "asdf");
	test = null;
	//强制释放资源
	System.gc();
  

 最后得到结果:

The object is to release: test1: qwer, test2: asdf

 由此可见,在对象被释放钱,finalize 的方法被调用了。

猜你喜欢

转载自rayfuxk.iteye.com/blog/2315726