
- Jython Tutorial
- Jython - Home
- Jython - Overview
- Jython - Installation
- Jython - Importing Java Libraries
- Jython - Variables and Data Types
- Jython - Using Java Collection Types
- Jython - Decision Control
- Jython - Loops
- Jython - Functions
- Jython - Modules
- Jython - Package
- Jython - Java Application
- Jython - Eclipse Plugin
- Jython - A Project in Eclipse
- Jython - NetBeans Plugin & Project
- Jython - Servlets
- Jython - JDBC
- Jython - Using the Swing GUI library
- Jython - Layout Management
- Jython - Event Handling
- Jython - Menus
- Jython - Dialogs
- Jython Useful Resources
- Jython - Quick Guide
- Jython - Useful Resources
- Jython - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Jython - Importing Java Libraries
One of the most important features of Jython is its ability to import Java classes in a Python program. We can import any java package or class in Jython, just as we do in a Java program. The following example shows how the java.util packages are imported in Python (Jython) script to declare an object of the Date class.
from java.util import Date d = Date() print d
Save and run the above code as UtilDate.py from the command line. Instance of the current date and time will be displayed.
C:\jython27\bin>jython UtilDate.py Sun Jul 09 00:05:43 IST 2017
The following packages from the Java library are more often imported in a Jython program mainly because standard Python library either does not have their equivalents or are not as good.
- Servlets
- JMS
- J2EE
- Javadoc
- Swing is considered superior to other GUI toolkits
Any Java package for that matter can be imported in a Jython script. Here, the following java program is stored and compiled in a package called foo.
package foo; public class HelloWorld { public void hello() { System.out.println("Hello World!"); } public void hello(String name) { System.out.printf("Hello %s!", name); } }
This HelloWorld.class is imported in the following Jython Script. Methods in this class can be called from the Jython script importex.py.
from foo import HelloWorld h = HelloWorld() h.hello() h.hello("TutorialsPoint")
Save and execute the above script from the command line to get following output.
C:\jython27\bin>jython importex.py Hello World! Hello TutorialsPoint!