我有两个类,每个类都有一个main方法,它将成为入口点的主类是RunPattern类。问题是,当在RunPattern类中调用DataCreator.serialize(fileName)时,将首先调用DataCreator类中的哪个方法?是main()方法还是serialize()?它与静态范围不同吗?
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.FileOutputStream;
public class RunPattern {
public static void main(String args[]){``// The first main() method
if(!new File("data.ser").exists()){
DataCreator.serialize("data.ser");
}
}
}
class DataCreator {
private static final String DEFAULT_FILE = "data.ser";
public static void main(String args[]){ // the second main
String fileName;
if(args.length == 1){
fileName = args[0];
}else{
fileName = DEFAULT_FILE;
}
serialize(fileName);
}
public static void serialize(String fileName){
try{
serializeToFile(createData(), fileName);
}catch(IOException exc){
exc.printStackTrace();
}
}
private static Serializable createData(){
ToDoListCollection data = new ToDoListCollectionImpl();
ToDoList listOne = new ToDoListImpl();
ToDoList listTwo = new ToDoListImpl();
ToDoList listThree = new ToDoListImpl();
listOne.setListName("Daily Routine");
listTwo.setListName("Programmer Hair Washing Product");
listThree.setListName("Reading List");
listOne.add("get up");
listOne.add("Brew cuppa java");
listOne.add("Read JVM Times");
listTwo.add("Latter");
listTwo.add("Rinse");
listTwo.add("Repeat");
listTwo.add("eventually throw too much conditioner");
listThree.add("the complete of duke");
listThree.add("how green was java");
listThree.add("URL, sweet URL" );
data.add(listOne);
data.add(listTwo);
data.add(listThree);
return data;
}
public static void serializeToFile(Serializable data, String fileName) throws IOException {
ObjectOutputStream serOut = new ObjectOutputStream(new FileOutputStream(fileName));
serOut.writeObject(data);
serOut.close();
}
}
答案 0 :(得分:1)
好。如果您使用
运行程序java -cp ... RunPattern
然后调用main
类的RunPattern
方法。这反过来调用
DataCreator.serialize("data.ser");
只是调用serialize
类的方法DataCreator
。
main
方法。
答案 1 :(得分:0)
DataCreator的主要方法永远不会以这种方式调用。
Some info about setting the main method in the Manifest-File
由于您通常在IDE中进行开发,因此这是自动完成的
但您可以在Runconfiguration中选择哪个mainmethod作为入口点。