开发者

How to call java function from within Jython embedded?

开发者 https://www.devze.com 2023-03-05 06:48 出处:网络
I have created an PythonInterpreter object, and want to call a java function but keep getting the error:

I have created an PythonInterpreter object, and want to call a java function but keep getting the error:

Exception in thread "main" Traceback (most recent call last):
  File "<string>", line 1, in <module>
NameError: name 'jytest2' is not defined
Java Result: 1

How do you call a java function from a live running system?

public static void main(String ar开发者_如何转开发gs[])
    {      
        ModRet modRet = new ModRet();
        jytest();
    }

public void jytest()
    {
        PythonInterpreter interp = new PythonInterpreter();

        interp.exec("print \'Hello; jython has successfully been embedded!\'");
        interp.exec("print " + FPS);
        interp.exec("jytest2()");

    }

    public void jytest2()
    {
        System.out.println("HIHIHI");
    }


I generally find that I need to use the Object Factory pattern and invoke things via an Interface as described in the Jython Book - Chapter 10

I'm still not super-clear on what you're trying to accomplish, so I don't have any code for you; but I'm sure you'll find the book helpful.


By default, the current classpath is included in jython path. To access any method in the path, you should do an import.

package com.mycompany.jythontest;


import org.python.util.PythonInterpreter;


public class App 
{

  public static void sayHello(String hello) {
    System.out.println(hello);
  }

  public static void main( String[] args )
  {
      PythonInterpreter py = new PythonInterpreter();

      py.exec("from com.mycompany.jythontest import App");
      py.exec("App.sayHello('hello')");
  }
}

And if you want to access a java instance in jython, you can use py.set(string, object) to make it accessible in the context. (Just like javax.scripting)

      App app = new App();
      py.set("appinstance", app);
      py.exec("appinstance.sayHi('hello world')");
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号