gpt4 book ai didi

java - 反射方法多次调用构造函数

转载 作者:行者123 更新时间:2023-11-30 11:06:14 25 4
gpt4 key购买 nike

我正在使用自定义类加载器和反射启动 JavaFX GUI 应用程序,但是我似乎无意中多次调用应用程序构造函数,这会引发异常(使用一种单例模式来保证没有人尝试重新调用-初始化主应用程序类)。

当我从我的 Launcher 调用 startupMethod.invoke(instance); 时,MyApp 构造函数的 IllegalStateException 被抛出类。

public class MyApp extends Application {

private static MyApp instance = null;

private static boolean started = false;

public MyApp() {
if (instance != null) {
throw new IllegalStateException("MyApp already initialized");
}
instance = this;
}

public static MyApp getInstance() {
return instance;
}

public void startup() {
synchronized (LOCK) {
if (started == true) {
throw new IllegalStateException("MyApp is already running");
}
}
// do things to start the GUI, etc...
// ... ... ...
started = true;
launch(); // static method part of the JavaFX platform
}

@Override
public void start(final Stage stage) {
// do stuff to display GUI
}

}

.

public class Launcher {

public static void main(String[] args) {
new Launcher().start();
}

private void start() {
// create custom classloader ...
// ... ... ...
Class<?> myAppClass = myLoader.loadClass("com.something.MyApp");
// calls the MyApp constructor and sets the "instance" static var to "this"
Object instance = myAppClass.newInstance();

Method startupMethod = myAppClass.getMethod("startup");
// this seems to call the MyApp constructor again!, exception thrown...
startupMethod.invoke(instance);
}

}

如果我在 MyApp 构造函数中注释掉异常,应用程序启动得很好,但这意味着我仍然调用了构造函数两次,但我不确定为什么。我需要能够防止人们多次调用此构造函数。

编辑: 通过一些研究,似乎对静态方法 Application.launch() 的调用正在尝试构建 MyApp< 的新实例 在 JavaFX 应用程序线程上...

更新:

通过将静态方法添加到 MyApp 来修复,它只调用 Application.launch() 方法。从 Launcher 类,我只是加载 MyApp 类,然后调用静态方法,如:

public class MyApp extends Application {
public MyApp() {
if (instance != null) {
throw new IllegalStateException("Already initialized");
}
instance = this;
}
// other stuff
public static void startup() {
launch();
}
}

.

public class Launcher {
// other stuff
Class<?> myAppClass = myLoader.loadClass("com.something.MyApp");
Method startupMethod = myAppClass.getMethod("startup");
startupMethod.invoke(null, null);
}

最佳答案

Application.launch() 创建调用它的类的实例(必须是 Application 的子类)。这就是第二个实例的来源。

关于java - 反射方法多次调用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29375525/

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