Conditional import

I am thinking of adding a dbus function to a java program that uses swing, so scripts can be used to do some of the functions. This thing should work on windows as well where dbus is not available.

So I thought about 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 this is a good idea? Will this work? Is there a better way to do this?

+3


source to share


2 answers


It's somewhat unreliable to rely on a constructor to cast ClassNotFoundException

s, unfortunately (although it might work for your use case, right now).

I would load the class with with Class.forName

for more robust behavior (and at 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();
        }
    }
}

      

+7


source


Why is it so difficult? Just maintain a separate jar file for each platform. It makes dependencies much better, easily maintains them separately, extends with 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 are on, include the appropriate jar in the classpath. And a new instance of DBus appeared in the program request.



final SomeInterface bus = new DBus();

      

If your program is distributed using WebStart, you can even specify which bundle is for which platform.

+1


source







All Articles