gpt4 book ai didi

java - 有条件的进口

转载 作者:搜寻专家 更新时间:2023-11-01 01:44:43 24 4
gpt4 key购买 nike

我想在一个使用swing的java程序中加入dbus功能,这样就可以用脚本来实现一些功能。这个东西也必须在没有 dbus 的 Windows 上运行。

所以我想做以下事情:

dbus.java:

import dbus; //Whatever the module is called
class dbus implements some_interface {
//blah blah
}

dbus_fake.java

class dbus_fake implements some_interface {
//full of empty methods
}

dbus_manager.java

class dbus_manager {
static some_interface get_dbus() {
try {
return new dbus(); //This should fail when loading the class, because the imports are not satisfied.
} except {
return new fake_dbus();
}
}
}

你认为这是个好主意吗?行得通吗?有更好的方法吗?

最佳答案

不幸的是,依靠构造函数抛出 ClassNotFoundException 有点不可靠(尽管它现在可能适用于您的用例)。

我将使用 Class.forName 加载类以获得更可靠的行为(同时使用更多 Java-ish 名称;):

class DBusManager {
static SomeInterface getDBus() {
try {
return Class.forName("your.pkg.RealDBus")
.getConstructor()
.newInstance();
} catch(ClassNotFoundException e) {
return new FakeDBus();
}
}
}

关于java - 有条件的进口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14775466/

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