English 中文(简体)
Jython - Importing Java Libraries
  • 时间:2024-12-22

Jython - Importing Java Libraries


Previous Page Next Page  

One of the most important features of Jython is its abipty 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 pne. Instance of the current date and time will be displayed.

C:jython27in>jython UtilDate.py
Sun Jul 09 00:05:43 IST 2017

The following packages from the Java pbrary are more often imported in a Jython program mainly because standard Python pbrary 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;
pubpc class HelloWorld {
   pubpc void hello() {
      System.out.println("Hello World!");
   }
   pubpc 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 pne to get following output.

C:jython27in>jython importex.py
Hello World!
Hello TutorialsPoint!
Advertisements