Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I know at runtime if a JAR file is already in the classpath?

What is the best way to know at runtime if a particular JAR file is already in my classpath ? (if that is not the case I should add it at runtime).

I do not know in advance the name of the jar nor the classes in it. A user can select it. The jar represents a runtime plugable component (a driver in my problem).

like image 567
Sergio Avatar asked Dec 31 '25 12:12

Sergio


2 Answers

String classpath = System.getProperty("java.class.path")

this will give you what is on your classpath. you can then parse that for the jar file you want

like image 140
RNJ Avatar answered Jan 02 '26 01:01

RNJ


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.

Bear in mind, though, that loading a jar at runtime is not very simple, you need to mess with classloaders. As a rule (there are exceptions) that's not the way, you should be able to add explicitly the jar to the classpath before running.

Update: the updated question states that we don't know in advance "the name of the jar nor the classes in it"; if so, this answer obviously does not apply. And the answer will depend on your specific classloader. In the usual scenario, AlexAndas' answer should work.

like image 20
leonbloy Avatar answered Jan 02 '26 03:01

leonbloy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!