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?
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:
HibernateStuff.import.HibernateStuffImpl. That class can import Hibernate stuff.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.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With