How to implement optional support for a jar if ONLY it exists

jar, java

Solution

During your initialization, you could use `Class.forName` to look up one of the Hibernate classes, and if it throws a `ClassNotFoundException` catch it and you know Hibernate isn't in the environment — set a flag so that you know not to do Hibernate-specific things.

Note, though, that if any of your classes refers to Hibernate classes statically (e.g., via `import`), those classes won't load if Hibernate isn't in the class path. The usual way to deal with that is:

- Create an interface to your Hibernate-specific stuff, e.g. `HibernateStuff`.

- Only refer to the interface from your main code, and don't refer to any Hibernate classes in your main code via `import`.

- Have your Hibernate-specific stuff in a class implementing that interface, e.g., `HibernateStuffImpl`. That class can `import` Hibernate stuff.

- Once you've determined that Hibernate is in the classpath (via `Class.forName`), use `Class.forName` to load your `HibernateStuffImpl` and then use `Class#newInstance` to create an instance of it, assigning it to a variable of type `HibernateStuff`.

- Use that variable to call into your Hibernate-specific stuff.

- You might have a `HibernateStuffStub` class that implements the interface by doing nothing, and use that when Hibernate isn't loaded, so your code isn't peppered with conditional statements. (The JVM is very quick at no-op calls.)

...and of course, all of the above applies to anything, not just Hibernate.

Problem

I'm developing a jar library for utility use. I want to significantly reduce the dependencies on external jars/libraries, but provide native support for such a library if it exists in the class path. For instance, I want the library to provide routines that work with hibernate; however I don't want the application to die with an error if the hibernate jars are not present. Is there a way to implement this, without having to bundle the hibernate jars with my library?

Original source