A jar loader for jython. If you want add some jars to JVM in Jython, you can use the following class. Modified from:
http://www.jython.org/jythonbook/en/1.0/appendixB.html#working-with-classpath
这是一个修改版本的classPathHacker,用于在Jython里加载一个Jar给Java Code使用。不同于在sys.path里面添加jar。此方法可以让JavaCode也使用到新加载的Jar,而不仅仅是JythonCode. 添加sys.path的方法参见:http://my.oschina.…
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
class ClassPathHacker : | |
########################################################## | |
# from http://forum.java.sun.com/thread.jspa?threadID=300557 | |
# | |
# Author: SG Langer Jan 2007 translated the above Java to this | |
# Jython class | |
# Modified by: Linker Lin linker.lin@me.com | |
# Purpose: Allow runtime additions of new Class/jars either from | |
# local files or URL | |
###################################################### | |
import java.lang.reflect.Method | |
import java.io.File | |
import java.net.URL | |
import java.net.URLClassLoader | |
import jarray | |
import java | |
def addFile (self, s): | |
############################################# | |
# Purpose: If adding a file/jar call this first | |
# with s = path_to_jar | |
############################################# | |
# make a URL out of 's' | |
f = self.java.io.File (s) | |
u = f.toURL () | |
a = self.addURL (u) | |
return a | |
def addURL (self, u): | |
################################## | |
# Purpose: Call this with u= URL for | |
# the new Class/jar to be loaded | |
################################# | |
sysloader = self.java.lang.ClassLoader.getSystemClassLoader() | |
sysclass = self.java.net.URLClassLoader | |
method = sysclass.getDeclaredMethod("addURL", [self.java.net.URL]) #parameters.toArray()) | |
a = method.setAccessible(1) | |
jar_a = self.jarray.array([u], self.java.lang.Object) | |
b = method.invoke(sysloader, [u]) | |
return u | |
if __name__=="__main__": | |
from java.lang import * | |
jarloader=ClassPathHacker() | |
jarloader.addFile(r'./mysql-connector-java-5.1.21.jar') | |
Class.forName("com.mysql.jdbc.Driver") | |
import sys | |
#sys.path+=[r'./mysql-connector-java-5.1.21.jar'] # unnecessary | |
import com.mysql.jdbc.Driver |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice, I tried with this method. It works with Teradata JDBC driver.
The code is shorter now.