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.forNameto look up one of the Hibernate classes, and if it throws aClassNotFoundExceptioncatch 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 canimportHibernate stuff.Class.forName), useClass.forNameto load yourHibernateStuffImpland then useClass#newInstanceto create an instance of it, assigning it to a variable of typeHibernateStuff.HibernateStuffStubclass 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.