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!
No comments:
Post a Comment