Calling JPython functions and passing parameters for Java

Randy Hudson rgh at inmet.com
Tue Oct 31 17:16:54 EST 2000


"Andre M. Descombes" wrote:

> I have a Java application and I would like to use JPython as a scripting
> language.
> What I want to do is for my Java code to fire JPython "Events" that get the
> parameters they need to do useful things. So what I do is I create a string
> which contains all Python code, and then use PythonInterpreter.Exec to
> compile it I then call each function by name:
> PythonInterpreter.Eval("funcname(params)"). The problem is this is extremely
> slow, I would like to call the JPython functions directly withoug going
> throughe the string search, unfortunately I haven't found any docs on how to
> do this? I would need something to get the python object of the function and
> then call it with some parameters.
> 
> Any ideas on how to do this? Any help will be appreciated!

The event listener pattern works well for this. In Java, you define a listener
interface, which declares the callback method(s) to be called when the
interesting
events occur, and a way of registering listener objects. (The pattern shows up
a lot in Java, especially in Swing: for example, look at 
java.beans.PropertyChangeListener.) Then in JPython you define the
actual listener, and register it. For instance, a property change listener
might look something like:

## start of script
from java.beans import PropertyChangeListener
from myApplication import ListenerManager
# ListenerManager has a static method addPropertyChangeListener

class MyPropertyChangeListener(PropertyChangeListener):
  def __init__(self):
    # blah blah blah
  def propertyChange(self,event):
    # method is declared in interface PropertyChangeListener as:
    # public abstract void propertyChange( java.beans.PropertyChangeEvent event
)
    print "property", event.propertyName, "is now", event.newValue

ListenerManager.addPropertyChangeListener( MyPropertyChangeListener() )
## end of script

Depending on how you exec the script, you could have the listener manager
be part of the environment in which the script executes.

-- Randy Hudson



More information about the Python-list mailing list