Java – how do I know at run time if a jar file already exists in the classpath?

If a particular jar file is already in my classpath, what is the best way to know at run time? If this is not the case, I should add it at runtime

I didn't know the name of the jar or the class in it The user can select it Jar represents a runtime pluggable component (the driver in my problem)

Solution

A practical method: class Forname ("com. MyClass"), where com MyClass is a class in your target jar (and only in it); If classnotfoundexception is thrown, the jar is not on your current classpath

But remember, loading a jar at runtime is not easy. You need to mess up the class loader Usually (with exceptions) this is not the case. You should be able to explicitly add jars to the classpath before running

Update: the update problem indicates that we do not know "the name of the jar or the class in it" in advance; If so, the answer is obviously not applicable The answer depends on your particular class loader In general, Alex andas's answer should be valid

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>