gpt4 book ai didi

java - 遇到这段代码,我想知道为什么需要这个静态辅助方法?

转载 作者:行者123 更新时间:2023-12-01 13:00:44 25 4
gpt4 key购买 nike

我没有编写此代码,所有功劳都归托管该链接的人所有。所以这里是代码的链接,编写它的人也列在 github 上......链接 -Github SourceCode-

这是方法预览:(参见下面的类)

//helper method
public static List readFile(String filePath) throws IOException {
return new TextFileReader(filePath).readFile();
}

等一下,我想我现在可能明白了,这只是为了让某人可以调用 readFile() 方法而不依赖于此对象,还是我错了?

如果有人想要了解该项目的较低级别 View ,这里是 git 上该项目的链接。我四处搜寻,只看到辅助方法分解了更大的任务,这是我对它们的最初理解。然而,我在 github 上,发现了这个:(从页面底部调出的方法,以便于查看,但也在类代码中。如果有人想更好地了解的话,这里还有一个 git 的链接......感谢您的任何回复或编辑看起来很正常,直到页面底部的静态辅助方法

public class TextFileReader implements FileReaderStrategy<String> {

private static final FileType FILE_TYPE = FileType.TEXT_FILE;
private String filePath;

public TextFileReader(String filePath) {
this.filePath = filePath;
}

@Override
public List<String> readFile() throws IOException {
List lines = new ArrayList();
BufferedReader in = null;
try {
in = new BufferedReader(
new FileReader(filePath));
String line = in.readLine();
while (line != null) {
lines.add(line);
line = in.readLine();
}
} catch(IOException ioe){
throw ioe;
}finally{
if(in != null){
in.close();
}
}

return lines;
}

//helper method
public static List readFile(String filePath) throws IOException {
return new TextFileReader(filePath).readFile();
}

}

最佳答案

你是对的。尽管我想说的是,这样可以在 Class 上调用该方法,而不是在该类的对象或实例上调用。

例如,静态方法可以这样调用:

TextFileReader.readFile(<filepath>);

无需首先创建该类的实例。

关于java - 遇到这段代码,我想知道为什么需要这个静态辅助方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23531740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com