Java-匿名内部类生命周期 [英] Java - Anonymous Inner Class Life Cycle

查看:163
本文介绍了Java-匿名内部类生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用匿名内部类作为PropertyChangeListener时,在对象生命周期的哪个点收集了类垃圾?回收包含的类(SettingsNode)之后?我应该在包含类(SettingsNode)的终结器中显式删除PropertyChangeListener吗?

When using an anonymous inner class as a PropertyChangeListener at what point in the object life cycle is the class garbage collected? After the containing class (SettingsNode) is reclaimed? Should I explicitly remove the PropertyChangeListener in the finalizer of the containing class (SettingsNode)?

public class SettingsNode extends AbstractNode
{
    public SettingsNode(Project project, ProjectSettings projectSettings)
        throws IntrospectionException
    {   
        // use an anonymous inner class to listen for changes
        projectSettings.addPropertyChangeListener(ProjectSettings.PROP_NAME,
            new PropertyChangeListener()
            {
                @Override
                public void propertyChange(PropertyChangeEvent evt)
                {
                   // handle event
                }
            });
     }
}

推荐答案

与所有对象一样,当匿名内部类的最后一个引用不再引用该内部类时,该匿名内部类也可以进行垃圾回收.我在这里使用狡猾的措辞,因为Java不保证所有事情都是GC.唯一的保证就是只要有参考就不会发生.

Like all objects, the anonymous inner class is eligible for garbage collected when the last reference to it no longer references it. I'm using weasel wording here because Java doesn't guarantee that things will be GC'd – the only guarantee is that it won't happen as long as there is a reference.

在这种情况下,就是 projectSettings 执行 removePropertyListener()或自身被垃圾回收的时候.

In this particular case, that would be when projectSettings either does a removePropertyListener() or is itself garbage collected.

因为 projectSettings 引用了匿名内部类,并且由于内部类引用了它的包含类,所以这意味着包含类也将至少与内部类一样长.

Because projectSettings references the anonymous inner class and because the inner class references its containing class, that means the containing class will also live at least as long as the inner class.

这篇关于Java-匿名内部类生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆