Top  | Previous | Next

Accessing Java

When programming Python in Ignition, your code executes in the Jython implementation of Python. (See About Scripting - Python or Jython?). While this doesn't have any great effect on the Python language itself, one of the great side benefits is that your Python code can seamlessly interact with Java code, as if it were Python code. This means that your Python code has access to the entire Java standard library, which is saying a lot.

 

To use Java classes, you simple import them as if they were Python modules. For example, the following code will print out all of the files in the user's home directory. This code uses the Java classes java.lang.System and java.io.File to look up the user's home directory and to list the files. Notice that we can even use the Python-style for loop to iterate over a Java sequence.

 

from java.lang import System

from java.io import File

 

homePath = System.getProperty("user.home")

homeDir = File(homePath)

 

for filename in homeDir.list():

   print filename

 

You can find the reference documentation for the Java standard class libraray (a.k.a. the "JavaDocs") here: http://docs.oracle.com/javase/6/docs/api/

 

Subclassing Java

eyeglasses You can even create Python classes that implement Java interfaces. If this is greek to you - don't worry, it isn't crucial. You'd need some understanding of Java and object-oriented programming concepts, which are outside the scope of this manual.

 

To create a Python class that implements a Java interface, you simply use the interface as a superclass for your Python class. For example, we could augment the example above to use the overload java.io.File.list(FilenameFilter). To do this, we'll need to create a FilenameFilter, which is an interface in Java that defines a single function:

boolean accept(File dir, String name)

 

To implement this interface, we create a Python class that has java.io.FilenameFilter as its superclass, and implements that Java-style function in a Python-esque way.

 

from java.lang import System

from java.io import *

 

class ExtensionFilter(FilenameFilter):

   def __init__(self, extension=".txt"):

      self.extension=extension.lower()

 

   def accept(self, directory, name):

      # make sure that the filename ends in the right extension

      return name.lower().endswith(self.extension)

         

 

homePath = System.getProperty("user.home")

homeDir = File(homePath)

 

# prints out all .txt files

for filename in homeDir.list(ExtensionFilter()):

   print filename

 

# prints out all .pdf files

for filename in homeDir.list(ExtensionFilter(".pdf")):

   print filename