Re: Reference to a class that does not exist
Brendan Guild wrote:
I am wondering when it is safe to mention a class that I know will be
impossible to load. Specifically, I am writing a Java library and
there is another library that has some very useful features, but I
don't expect that other library to always be available.
[snip uncertainty about JLS]
I want to do this in a way that is guaranteed to be correct by Java,
not just a way that happens to work at the whim of the JVM that I am
using.
You're concerned that the link error might be allowed to occur so early
as to prevent an application, which is using your library, from running,
right?
Assuming it is deemed to be a problem...
Define an interface for doing some operation provided by the optional
library:
interface EdgeDetector {
Image detectEdges(Image source, int threshold);
}
Create an implementation that actually uses the optional library:
class SomeLibEdgeDetector implements EdgeDetector { ... }
In your library, when you need to do this operation (or to determine
whether it can be done), identify the class by String:
EdgeDetector ed = null;
try {
Class edc = Class.forName("SomeLibEdgeDetector");
ed = edc.newInstance();
} catch ( various exceptions... ) {
// Ignore.
}
If the optional library isn't available, ed should be null. I'm
assuming that at least one of the calls in the try block will throw
something straight-away, but even if not, you could still catch the
error when you make the call.
--
ss at comp dot lancs dot ac dot uk |