Created
June 19, 2018 17:13
-
-
Save ngo/2e694fe096273cf928424fc6f19938ff to your computer and use it in GitHub Desktop.
Dynamic loading of jython jars and classloader problems
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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