Java扫描仪最佳实践 [英] Java Scanner Best Practice
问题描述
问题: 我有一个使用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屋!