【问题标题】:Lifecycle of non-referenced objects as parameters非引用对象的生命周期作为参数
【发布时间】:2014-03-24 17:35:20
【问题描述】:

比如……

incomingTemplate = factory.newTemplates(new StreamSource(Utils.getResource(...

StreamSource 对象是未引用的(有没有更好的说法?)因此不能调用它的 close 方法来确保它的资源被清除。

这些对象与普通的局部变量有什么不同吗?这是否受对象引用(incomingTemplate)是否为静态的影响?

【问题讨论】:

    标签: java object lifecycle


    【解决方案1】:

    这段代码

    StreamSource ss = new StreamSource(Utils.getResource());
    incomingTemplate = factory.newTemplates(ss);
    

    等于

    incomingTemplate = factory.newTemplates(new StreamSource(Utils.getResource()));
    

    唯一的区别是,如果您使用第二种变体,您将无法再直接访问 StreamSource。


    但是如果incomingTemplate 有getStreamSource 方法,那真的没关系,如果你使用这个:

    StreamSource ss = new StreamSource(Utils.getResource());
    incomingTemplate = factory.newTemplates(ss);
    

    或者这个:

    incomingTemplate = factory.newTemplates(new StreamSource(Utils.getResource()));
    StreamSource ss = incomingTemplate.getStreamSource();
    

    【讨论】:

    • 关于生命周期,StreamSource 是否隐式为 null,因为它一旦用于创建 Template 对象就没有被引用?
    猜你喜欢
    • 1970-01-01
    • 2016-09-29
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 2015-09-03
    • 1970-01-01
    • 1970-01-01
    • 2011-04-28
    相关资源
    最近更新 更多