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 的方法被调用了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值