This is a method to import the class in the jar file directly from the Python script.
It doesn't depend on CLASSPATH, so if you have an environment where Java and Jython can run It makes it possible to easily package the integration between Python and Java.
This is useful, for example, when you want to use Java's legacy and SQLite at the same time in Python. Jython is a standard module and does not support SQLite, so a JDBC driver is required, If you can read the JDBC driver jar file directly from the Python script, You can use Java classes and SQLite from Python just by throwing in the files you need.
test.py
import.sys
sys.path.append("/path/to/hogehoge.jar")
import Hogehoge
It works with! There was information that it was useless. It seems that you have to load the classes in it, not just pass it through.
ClassPathHacker
ClassPath Hacker seems to be one solution. http://www.jython.org/jythonbook/en/1.0/appendixB.html#working-with-classpath
The following is an example of calling the JDBC driver of sqlite from jython.
test2.py
from java.lang import Class
from java.sql import DriverManager
class classPathHacker:
import java.net.URLClassLoader
def addFile(self, s):
sysloader = self.java.lang.ClassLoader.getSystemClassLoader()
sysclass = self.java.net.URLClassLoader
method = sysclass.getDeclaredMethod("addURL", [self.java.net.URL])
method.setAccessible(1)
f = self.java.io.File(s)
method.invoke(sysloader, [f.toURL()])
c = classPathHacker()
c.addFile("/path/to/sqlite-jdbc.jar")
jdbc_url = "jdbc:sqlite:/path/to/database.db"
driver = "org.sqlite.JDBC"
Class.forName(driver).newInstance()
con = DriverManager.getConnection(jdbc_url)
#Below
I'm not sure, but forcibly make URLClassLoader.addURL accessible It looks like you're loading a class.
Recommended Posts