tags:

views:

90

answers:

3

I would like to be able to do something like (psuedo-code):

if (classAvailable) {
    // do a thing
} else {
    // do a different thing
}

What would be even better is if I could extend a class from ClassA if it's available or ClassB, if it isn't. I suspect this isn't possible though.

+4  A: 

You can do the first part:

try {
    Class.forName("my.ClassName");
    // It is available
}
catch (ClassNotFoundException exception) {
    // It is not available
}
John Kugelman
That won't help if it still tries to reference it statically ...
Noon Silk
A static `my.ClassName` reference will just fail to compile if the class isn't available at compile time. That's a no go if the class "may" or "may not" be available.
John Kugelman
+1  A: 

I don't think there's a way to dynamically choose whether to extend one class or another, except if you made a program that can manipulate bytecode directly (simple example: hold the compiled bytecode for both versions of the subclass as strings, and just use a ClassLoader to load whichever one corresponds to the superclass you have available).

You could do it in Python, though ;-)

David Zaslavsky
+2  A: 

My usual approach to this is:

Separate out the code which uses the optional library into a different source directory. It should implement interfaces and generally depend upon the main source directory.

In order to enforce dependencies in the build, compile the main source directory without the optional library, and then the source that depends on the optional library (with other class file from other source directory and the library on the compiler classpath).

The main source should attempt to load a single root class in the optional source directory dynamically (Class.forName, asSubclass, getConstructor, newInstance). The root class' static intialiser should check that the library is really available and throw an exception if it is not. If the root class fails to load, then possibly follow the Null Object pattern.

Tom Hawtin - tackline