如何在另一个类中调用一个类的 main() 方法?
Posted
技术标签:
【中文标题】如何在另一个类中调用一个类的 main() 方法?【英文标题】:How do I invoke a main() method of one class in another class? 【发布时间】:2015-08-08 05:18:52 【问题描述】:如何在另一个类中调用一个类的main()
方法?我有两个班级SaveData
和DynamicTest
。这两个类都包含一个main()
方法。我想在DynamicTest
类中运行我的主程序。如何正确拨打SaveData
?
public class SaveData
private static final Map<String, Object> myCachedTreeMap = new TreeMap<String, Object>();
public static final List<String> getLines(final String resourceParam, final Charset charset) throws IOException
System.out.println("Please get: "+resourceParam);
if (myCachedTreeMap.containsKey(resourceParam) )
// Use the cached file, to prevent an additional read.
System.out.println("Found in memory : "+resourceParam);
else
// Load the file from disk
System.out.println("Not Found in memory : "+resourceParam);
return null;
public static void main(String[] args) throws IOException
String target_dir = "C:\\myfiles\\config\\en";
String output = "C:\\myfiles\\config\\en\\output.txt";
File dir = new File(target_dir);
File[] files = dir.listFiles();
if (files == null || files.length < 1)
System.out.println("File list is empty...");
return;
// open the Printwriter
PrintWriter outputStream = new PrintWriter(output);
try
for (File textFile : files)
if (textFile.isFile() && textFile.getName().endsWith(".txt"))
readFromDisk(textFile);
finally
outputStream.close();
String fileNameFromCache = "en_synonyms.txt";
Object Sheet1 = myCachedTreeMap.get(fileNameFromCache);
System.out.println(fileNameFromCache + " : \n" + Sheet1);
@SuppressWarnings("resource")
private static void readFromDisk(File textFile) throws FileNotFoundException, IOException
BufferedReader inputStream;
inputStream = null;
String content = "";
try
inputStream = new BufferedReader(new FileReader(textFile));
content = readFile(textFile);
System.out.println("Bytes Read = "+content.length());
// Save contents
FileContentsObject Sheet1 = new FileContentsObject(System.currentTimeMillis(),
textFile.lastModified(), content,
textFile.getName(),
getLines(null, null));
// add to map
myCachedTreeMap.put(textFile.getName(), Sheet1);
finally
if (inputStream != null)
inputStream.close();
private static String readFile(File f) throws FileNotFoundException, IOException, UnsupportedEncodingException
StringBuilder text = new StringBuilder(1024);
int read, N = 1024 * 1024;
char[] buffer = new char[N];
BufferedReader br = null;
try
br = new BufferedReader(
new InputStreamReader(
new FileInputStream(f), "UTF8"));
while(true)
read = br.read(buffer, 0, N);
if (read > 0)
text.append(new String(buffer, 0, read));
if(read < N)
break;
finally
if (br != null)
br.close();
return text.toString();
private static final class FileContentsObject
private long cachedTime; // currentTime
private long lastModifiedTimestamp;
private String contents;
List<String> lines;
private String fileName;
public FileContentsObject(long cachedTime, long lastModifiedTimestamp,
String contents, String fileName, List<String> lines)
this.cachedTime = cachedTime;
this.lastModifiedTimestamp = lastModifiedTimestamp;
this.contents = contents;
this.fileName = fileName;
this.lines = lines;
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
System.out.println("Current Time & Date:" + sdf.format(cachedTime));
System.out.println("Last Modified Time Stamp:"
+ sdf.format(lastModifiedTimestamp));
/**
*
* @return The lines from the file
*/
List<String> getLines()
return this.lines;
public String toString()
return "Sheet1" + "fileName='" + fileName + '\'' + ", contents='"
+ contents + '\'' + ", lastModifiedTimestamp="
+ lastModifiedTimestamp + ", CurrentTime&Date="
+ cachedTime + '';
public class DynamicTest
public static void main(String[] args)
Charset charset = Charset.forName("UTF-8");
try
List<String> lines = CacheData.getLines("en_synonyms", charset) ;
if (lines != null)
System.out.println("Number of Lines: "+lines.size());
for (String line:lines)
System.out.println("DynamicTest:: "+line);
catch (IOException e)
e.printStackTrace();
try
List<String> lines = CacheData.getLines("en_stopwords", charset) ;
if (lines != null)
System.out.println("Number of Lines: "+lines.size());
for (String line:lines)
System.out.println("DynamicTest:: "+line);
catch (IOException e)
e.printStackTrace();
【问题讨论】:
如果您不知道如何调用静态方法,您应该阅读教程。 您可以这样做,但不建议这样做。如果你只想从 DynamicTest 调用 SaveData 的main
方法,那么将 main 重命名为其他方法。我还看到你没有使用 args,所以你应该有一个没有任何参数的方法。
【参考方案1】:
您可以像调用任何其他静态方法一样调用它:
SaveData.main (args); // it's up to you whether to pass the same args or
// different args
【讨论】:
这个,但我建议不要使用大的main
方法。只需定义一个辅助方法并调用它。此外,IMO 不声明多个电源
@manutero 你能解释一下“不使用大的主要方法”是什么意思吗?
@FullNelson 将 big 更改为 long(对不起);您的 main 有大约 25 行与程序逻辑相关,只是良好的编码实践; From this answer 引用这一行: main() 并不真正属于我们日常类的数据和行为,因为我怀疑每个类都需要自己执行。 main() 关心的是运行我们的程序。 另外,see this question【参考方案2】:
在DynamicTest
的main方法中写这个SaveData.main(args);
静态方法调用:
Class.method();
非静态方法调用:
Class object = new Class();
object.method();
【讨论】:
【参考方案3】:Main declaration 始终为 static
,因此您必须像其他 static
方法一样调用它,在您的情况下:
SaveData.main (args);
【讨论】:
有两种主要方法相关的缺点吗?关于从 CacheData 中删除主要内容,我有哪些选择?以上是关于如何在另一个类中调用一个类的 main() 方法?的主要内容,如果未能解决你的问题,请参考以下文章