问题
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?
For example: (bare bone)
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);
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......
回答1:
You get a copy of the reference. So you'll still use the same object instance.
来源:https://stackoverflow.com/questions/12928616/java-scanner-best-practice