Chapter 12. Embedding Jython Inside Java

In the previous chapters we described how to build entire programs in Jython that are executed using the Jython interpreter. From a program being executed by the Jython interpreter you can access existing Java code within external libraries. You can write your entire program in Jython and use only preexisting Java libraries. Alternately, your program can be a hybrid of Java and Jython—for example, data crunching or graphics and visualization code in Java for performance reasons, and connecting logic and user interface code in Jython.

There is another way to use Jython. You can embed a Jython interpreter within your Java program. That interpreter could then execute Jython code and interact with the state of the parent Java program. The embedded interpreter can be used to manage various kinds of customization of the parent program. For example, you could write a system management framework that allows users to define responses to system events in Jython. You could create programmatic filters with all the power of the Python language to enhance, for example, an email client. You could use Jython for macro functionality in nearly any kind of program, or as a mechanism to separate game logic from a game engine.

While you could create an ad hoc solution or language for each of these problems, embedding a Jython interpreter has several advantages. If you are using Jython as your internal scripting language, you don’t need to spend time building an ...

Get Jython Essentials now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.