I have run into an issue while making a plugin that is dependent on another plugin.
How do I check to see if a .jar exists BEFORE importing it - and if it exists, than import it ? The other plugin has 3 different versions, each one is incompatible with the other versions.
Note: the other plugin actively runs on the server, so including copies of it inside of my own .jar will not work - and I have no clue which version each server has.
Any help would be greatly appreciated.
Check If JAR Exists Before Importing
I'm not entirely clear what you're trying to do exactly.
If you're trying to detect the presence of a jar file itself then you could check the filesystem, if you know where to look.
Alternatively perhaps what you want is to check whether a particular class, which may well happen to be packaged in that jar, is available on the classpath or classloader chain. In which case you could use Class.forName(String) and see whether it throws a ClassNotFoundException.
If you're trying to detect the presence of a jar file itself then you could check the filesystem, if you know where to look.
Alternatively perhaps what you want is to check whether a particular class, which may well happen to be packaged in that jar, is available on the classpath or classloader chain. In which case you could use Class.forName(String) and see whether it throws a ClassNotFoundException.
After a long time, I found the answer to my own question.
The way to load classes dynamically is to use a ClassLoader. Here is a good reference for how to do this. http://tutorials.jenkov.com/java-reflection/dynamic-class-loading-reloading.html
The way to load classes dynamically is to use a ClassLoader. Here is a good reference for how to do this. http://tutorials.jenkov.com/java-reflection/dynamic-class-loading-reloading.html
Also before writing your own class loader I'd recommend you check out URLClassLoader, see http://docs.oracle.com/javase/7/docs/api/java/net/URLClassLoader.html
With URL class loader you can load files from directories or jars in your file system, e.g.
[source lang="java"]URLClassLoader classLoader =
new URLClassLoader(new URL[]{ new URL("file:///pathToMy.jar") },
ClassLoader.getSystemClassLoader());
Object instance = classLoader.loadClass("package.AndNameOfMyClass").newInstance();[/source]
With URL class loader you can load files from directories or jars in your file system, e.g.
[source lang="java"]URLClassLoader classLoader =
new URLClassLoader(new URL[]{ new URL("file:///pathToMy.jar") },
ClassLoader.getSystemClassLoader());
Object instance = classLoader.loadClass("package.AndNameOfMyClass").newInstance();[/source]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement