I am doing a similar thing in jOOQ to load additional logging framework dependencies. I share your feelings about the fact that this is a little hack. An example of a field initialization code fragment, depending on the availability of the class:
public final class JooqLogger { private org.slf4j.Logger slf4j; private org.apache.log4j.Logger log4j; private java.util.logging.Logger util; public static JooqLogger getLogger(Class<?> clazz) { JooqLogger result = new JooqLogger();
And then, later, the registrar switch, depending on previously loaded classes:
public boolean isTraceEnabled() { if (slf4j != null) { return slf4j.isTraceEnabled(); } else if (log4j != null) { return log4j.isTraceEnabled(); } else { return util.isLoggable(Level.FINER); } }
The rest of the source code can be seen here . In fact, I have a compile-time dependency with both slf4j and log4j, which I render optionally at runtime using a similar template like you.
This can cause problems in OSGi environments, for example, when loading classes is a bit more complicated than using standard JDK / JRE loading mechanisms. However, so far I have not been informed of any problems.
source share