conditional import

2019-06-27 10:02发布

问题:

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.

So i was thinking of doing the following:

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?

回答1:

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

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


回答2:

Why so difficult ? Simply maintain a separate jar file for each platform. It makes the dependencies a lot better, easy to maintain it separately, extend with a new implementation, etc...

windows-dbus.jar
 |
 +- class DBus implements SomeInterface { fake code }


linux-dbus.jar
 |
 +- class DBus implements SomeInterface { real dbus code }

Depending on the platform you're on, include the appropriate jar in the classpath. And in the program request a new instance of DBus.

final SomeInterface bus = new DBus();

If your program is distributed with WebStart you can even mention what jar is destined to what platform.



标签: java import