条件导入 [英] conditional import

查看:136
本文介绍了条件导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑将dbus函数添加到使用swing的java程序中,因此脚本可用于执行某些功能。
这个东西也必须在windows上运行,dbus不可用。

I am thinking of adding dbus function to a java program that uses swing, so scripts can be used to perform some functions. This thing must run on windows too, where dbus is not available.

所以我想做以下事情:

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();
        }
    }
}

你认为它是好的吗?理念?会有用吗?有更好的方法吗?

Do you think it's a good idea? Would it work? Is there a better way of doing it?

推荐答案

依靠构造函数抛出 ClassNotFoundException s,不幸的是(虽然它可能适用于您的用例,现在)。

It is somewhat unreliable to rely on the constructor to throw ClassNotFoundExceptions, unfortunately (although it may work for your use case, right now).

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

I'd load the class using Class.forName for more reliable behavior (and in the same time use more Java-ish names ;):

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

这篇关于条件导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆