Using Java libraries with Jython

Using Java libraries with Jython

28 August 2019

Kilian Niemegeerts

It’s very easy to use and give access to all Java-libraries. Whether you’re stuck with an old version of Jython and you’re in need of some functionality that is developed in the last decade, or you need to access a Java-only library but your language of choice is Python; accessing Java via Jython seems to be the right solution. In this blog post we will show you how to use Java libraries in Jython, using books.xml as an example.

How to start

When using WebSphere prior to version 9, you remain stuck with an old version of Jython for administrative scripts. WebLogic’s wlst, on the other hand, is similarly challenged. Luckily the ‘J’ in Jython stands for Java, which means you’re having access to the whole ecosystem running on the JVM.

Python provides a limited XPath subset in its standard libraries; however, for full support, you’ll need a library like lxml, which exists only for CPython. If you are using Jython, you can use the Java libraries. In this blog post, we’ll take books.xmlas a sample.

Read the XML

Let’s start by reading the XML file and printing the number of books:

from javax.xml.parsers import DocumentBuilderFactory

builder = DocumentBuilderFactory.newInstance().newDocumentBuilder()
doc = builder.parse(‘books.xml’)

books = doc.getElementsByTagName(‘book’)
totalBooks = books.getLength()
print(‘Total number of books: %s’ % totalBooks)

Easily put: just simply import DocumentBuilderFactorylike you would import a Python library. Creating a builderis a bit more tedious than using a standard Python library, but it’s not difficult either. Getting the number of items doesn’t work with len(), so you’ll need to call getLength().

Once again, it’s no rocket science: expr.evaluate returns a NodeList instead of a Python list, so we need to iterate over it by calling the item() method, with an index as a parameter.

It’s very straightforward to call Java libraries from Jython, allowing you to tap into the vast Java ecosystem. However, the libraries you’re using are made with Java in mind, which means that your resulting code will look like a mix between Java and Python.

Now it’s time for the real thing, so test and try it out at your own pace! If you have further questions about using Java libraries with Jython, or if something isn’t quite clear; don’t hesitate to contact us!

Would you like to know more about our tips & tricks, the team and our adventures? Then make sure to read our other blog posts!

Related posts
No Comments

Sorry, the comment form is closed at this time.