If I use
try { Class.forName("my.package.Foo"); // it exists on the classpath } catch(ClassNotFoundException e) { // it does not exist on the classpath }
the static initializer block of "Foo" is kicked off. Is there a way to determine whether a class "my.package.Foo" is on the classpath without kicking off its static initializer?
We can check for the existence of a class using Java Reflection, specifically Class. forName(). The documentation shows that a ClassNotFoundException will be thrown if the class cannot be located.
To check our CLASSPATH on Windows we can open a command prompt and type echo %CLASSPATH%. To check it on a Mac you need to open a terminal and type echo $CLASSPATH.
A pragmatic way: Class. forName("com. myclass") where com. myclass is a class that is inside (and only inside) your target jar; if that throws a ClassNotFoundException , then the jar is not on you current classpath.
Try the forName(String name, boolean initialize, ClassLoader loader)
method of Class
and set the param initialize
to false
.
JavaDoc link
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