Java扫描仪最佳实践 [英] Java Scanner Best Practice

查看:76
本文介绍了Java扫描仪最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题: 我有一个使用BufferedReader实例化新的Scanner类并返回Scanner类本身的方法.据我了解,Java将返回Scanner类-作为对象的副本"(传递值),而不是在C ++中将其称为引用"或指针".只要逻辑是正确的-那是否意味着在我调用的方法中实例化的Scanner将继续保持OPEN状态,从而永远不会被垃圾回收?

Question: I have a method that Instantiates a new Scanner Class with a BufferedReader, and returns the Scanner Class itself. As far as I understand it, Java will return the Scanner class - as a "copy" of the object (pass-by-value), as opposed to what we would call in C++ a Reference or Pointer. Provided that logic is correct - does that then mean, the Scanner instantiated in the method I call, will continue to stay OPEN and thus never be garbage collected?

例如:(裸露的骨头)

private Scanner getDataFromWebService(String url)
{
    URLConnection sc = null;
    URL test = null;
    Scanner scanner = null;

    test = new URL(url);
    sc = test.openConnection();
    in = new BufferedReader(new InputStreamReader(sc.getInputStream());

    scanner = new Scanner(in);

    return scanner;
}

// Sample Call

Scanner newScanner = getDataFromWebService(url);

其次,如果您愿意这样做的话;然后,URLConnection和BufferedReader会发生什么,因为如果我在使用getDataFromWebService方法返回扫描器之前将它们关闭,则会无效化"返回的扫描器.也许答案就在第一个问题中.

Secondly if you would be so kind to oblige; what happens then to the URLConnection and the BufferedReader, because if I close them before returning the Scanner in the getDataFromWebService Method - it will 'nullify' the returned Scanner. Perhaps the answer to this lies in the first question.

这里最好的做法是,永远不要返回复杂的对象……

What would be best practice here, just never returning a complex object......

推荐答案

您将获得引用的副本.因此,您仍将使用相同的对象实例.

You get a copy of the reference. So you'll still use the same object instance.

这篇关于Java扫描仪最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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