Exclude library from Java Classpath

I have a multiproject and have a compile error that a symbol cannot be found from a StringUtils class.
Obviously i have several StringUtils classes on the classpath, one from the hibernate package, another from some ant lib and the right one from the apache.commons.lang dependency.

What is the best option to force the project to use the apache.commons.lang package and not the other ones.
Can i exclude java libraries from the classpath? Or is there a better option?

If it’s on your classpath, it’s available for use. If you were to remove the hibernate StringUtils somehow from the classpath (ie deleting it from the jar) it would likely break hibernate. The nuclear option is to somehow run hibernate in another classloader but I really wouldn’t recomment it.

Unless, of course, the hibernate jars are split into interfaces/annotations and implementation jars. In which case you could put the interface jar on the compile classpath and the implementation only on the runtime classpath. I haven’t used hibernate in quite a while (I think it’s a really bad idea but that’s a conversation for another day)

If you are using eclipse, you can tell it to remove/filter some options from content assist so they are never suggested (I often remove java.awt.* to prevent the awt list from being suggested by content assist). I’m sure intellij has a similar option

@see Preferences --> Java --> Editor --> Content Assist --> Type Filters

Or perhaps you could run a regex over your source code and fail the build if you detect blacklisted class usage.

Using wildcards in java classpath

Wild cards were introduced from Java 6. Class path entries can contain the basename wildcard character *, which is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR. For ex. a classpath entry consisting simply of * expands to a list of all the jar files in the current directory.

Example

java -cp “lib/*” %MAINCLASS%

More about…Java Classpath

Anto