I'm using some vendor's SDK that works fine if the JAR is provided by me. I want to dynamically load the JAR from a custom path that will be provided in properties file / system environment variable. And load the this JAR, just before executing the class that wraps the SDK code.
I've started to write the following code: But I'm not sure which method will actually load the class. Maybe I'm not using the right API for that? (Using dynamic class path with a script is not an option here, I know . . .)
public void load(String path) {
String className = getClassName();
if (Utils.isNullOrEmpty(path)) {
return;
}
if (initialized) {
System.out.println("Already loaded classe " + className);
return;
}
try {
System.out.println("path = " + path);
URL[] jars = new URL[]{new URL("file", "", path)};
System.out.println("url = " + jars[0]);
try (URLClassLoader classLoader = URLClassLoader.newInstance(jars)) {
classLoader.loadClass(className);
System.out.println("classLoader.loadClass(getClassName()) worked");
Class.forName(className);
System.out.println("Class.forName(getClassName()) worked");
ClassLoader.getSystemClassLoader().loadClass(className);
System.out.println("ClassLoader.getSystemClassLoader().loadClass(getClassName()) worked");
initialized = true;
log.debug("Succeeded loading class ");
} catch (IOException e) {
log.error("Failed to load SDK from path: {}. Error: {}", path, e.getMessage());
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("Error to load: " + e.getMessage());
}
} catch (MalformedURLException e) {
System.out.println("Failed to load SDK from path: {}. Error: {} " + path + e.getMessage());
}
}
I've tried to use the Java ClassLoader which I'm not sure is the right API here, a colleague insists that it is. (I think that it's only for Reflection use) I've found also a link about Java agent which I haven't tried yet.
I saw other similar questions, but I want to make sure this ClassLoader is not the right method for our use. And if so I'll try something else. Thanks