【发布时间】:2019-02-12 04:10:24
【问题描述】:
我有以下代码。
public static void main(String[] args)
{
if (!ArgumentsHandler.handle(args))
{
return;
}
Storage.getInstance().load();
if (!Storage.getInstance().isLoadSuccessful())
{
launch(args);
}
else
{
System.err.println("Unable to load configurations.");
}
}
我专门反转了 if 语句中的条件以使其失败,我可以在调试器中明确看到它没有执行 launch 方法,但仍显示应用程序窗口。
我还注意到,在 main 方法中使用 return 语句没有任何效果 - 应用程序仍在继续执行。它只响应System.exit(0)。
为什么会这样?
更新:
根据您的要求,这是 ArgumentsHandler 的 sn-p。我在这里没有使用线程(至少是有意的)。
public static boolean handle(String[] args)
{
//handle args
if (args.length > 0)
{
switch (args[0])
{
//createRepository
case "-c":
configure(args);
break;
case "-r":
case "--repository":
repository(args);
break;
default:
help();
break;
}
return false;
}
return true;
}
private static void configure(String[] args)
{
if (args.length > 1)
{
boolean isRandom = false;
switch (args[1])
{
case "true":
case "1":
isRandom = true;
break;
case "false":
case "0":
//valid input, ignored
break;
default:
System.err.println("Invalid arguments. Possible values: [--configuration] [1/0].");
return;
}
Storage.configure(isRandom); //creates a bunch of json files (uses NIO).
return;
}
else
{
System.err.println("Invalid arguments. Possible values: -c [1/0].");
}
}
存储
public void load()
{
isLoadSuccessful = false;
//load configuration
app = loadConfiguration(appFilePath);
if (app == null)
{
System.err.println("Unable to load app configuration.");
return;
}
//load company
company = loadCompany(app.getCompanyFilePath());
if (company == null)
{
System.err.println("Unable to load company configuration.");
return;
}
repository = loadRepository(app.getRepositoryFilePath());
if (repository == null)
{
System.err.println("Unable to load repository configuration.");
return;
}
isLoadSuccessful = true;
}
private static App loadConfiguration(String filePath)
{
return (App) Utility.load(filePath, App.class);
}
loadConfiguration、loadCompany 和 loadRepository 真的是一样的。将来,他们不会读取简单的 json 文件,而是会访问复杂的档案,这就是为什么我已经创建了几个几乎相同的方法。
实用程序.load
public static Object load(String path, Type type)
{
try
{
JsonReader reader = new JsonReader(new FileReader(path));
Gson gson = new Gson();
Object obj = gson.fromJson(reader, type);
reader.close();
return obj;
}
catch (IOException ex)
{
ex.printStackTrace();
return null;
}
}
只是从文件中反序列化对象。
【问题讨论】:
-
能否请您出示
ArgumentsHandler.handle(...)和Storage.load()的代码sn-ps?我假设其中一种方法会产生一个非守护线程,它会阻止进程在离开main方法后结束。 -
main方法是从主线程调用的,你
return不代表你退出了线程。您的进度不足以启动窗口,但也没有明确告诉线程退出,因此您会遇到应用程序停顿。我不确定您在main方法中尝试做什么,但如果您尝试使用return,那么您可能还是想退出。 -
@trylimits 添加到问题中。
-
调试的时候可以检查是否有其他线程在运行(除了主线程)。如果您使用 Eclipse,您可以在 Debug View 中看到正在运行的线程:help.eclipse.org/photon/…
-
从您调用
launch的方式来看,我假设main在Application子类中。我发现在Application类中包含main会导致某种初始化,一旦main退出,就会阻止JVM 退出。尽管没有调用launch,但仍会发生这种情况。我猜这与 Java 启动 JavaFX 应用程序的特殊方式有关,因为将main移动到另一个类不会导致这个问题。而且它不是由Application类引起的,因为手动初始化该类也不会导致此问题。