Instantly share code, notes, and snippets.

@ngo /Main.java
Created Jun 19, 2018

Embed
What would you like to do?
Dynamic loading of jython jars and classloader problems
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
public class Main {
public static void main(String[] args) {
try {
URL[] classUrls = {new URL("file:///path/to/jython-standalone.jar")};
ClassLoader oldcl = Thread.currentThread().getContextClassLoader();
URLClassLoader urlcl = new URLClassLoader(classUrls, oldcl);
//!!!!! Comment the following line and you will get an error
Thread.currentThread().setContextClassLoader(urlcl);
Class interpreter = Class.forName("org.python.util.PythonInterpreter", true, urlcl);
Method exec = interpreter.getDeclaredMethod("exec", String.class);
Object instance = interpreter.newInstance();
Object result = exec.invoke(instance,"import xml.etree.ElementTree as ET");
result = exec.invoke(instance,"ET.fromstring('<test></test>')");
//Restore the classloader (optional
Thread.currentThread().setContextClassLoader(oldcl);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment