TeslaXba
TeslaXba

Reputation: 357

Jython - Calling Python Class in Java

I want to call my Python class in Java, but I get the error message:

Manifest com.atlassian.tutorial:myConfluenceMacro:atlassian-plugin:1.0.0-SNAPSHOT : Classes found in the wrong directory

I installed Jython on my pc via jar. And added it in my pom (because I am using a Maven Project). What am I doing wrong? How can I call a python method inside my java class?
I am using python3.

POM

<!-- https://mvnrepository.com/artifact/org.python/jython-standalone -->
<dependency>
    <groupId>org.python</groupId>
    <artifactId>jython-standalone</artifactId>
    <version>2.7.1</version>
</dependency>

JAVA CLASS

package com.atlassian.tutorial.javapy;
import org.python.core.PyInstance;  
import org.python.util.PythonInterpreter;  


public class InterpreterExample  
{  

   PythonInterpreter interpreter = null;  


   public InterpreterExample()  
   {  
      PythonInterpreter.initialize(System.getProperties(),  
                                   System.getProperties(), new String[0]);  

      this.interpreter = new PythonInterpreter();  
   }  

   void execfile( final String fileName )  
   {  
      this.interpreter.execfile(fileName);  
   }  

   PyInstance createClass( final String className, final String opts )  
   {  
      return (PyInstance) this.interpreter.eval(className + "(" + opts + ")");  
   }  

   public static void main( String gargs[] )  
   {  
      InterpreterExample ie = new InterpreterExample();  

      ie.execfile("hello.py");  

      PyInstance hello = ie.createClass("Hello", "None");  

      hello.invoke("run");  
   }  


} 

Python Class

class Hello:  
    __gui = None  

def __init__(self, gui):  
    self.__gui = gui  

def run(self):  
    print ('Hello world!')

Thank you!

Upvotes: 0

Views: 1120

Answers (1)

Alex
Alex

Reputation: 654

You have wrong indentation in your Python class. Correct code is:

class Hello:  
    __gui = None  


    def __init__(self, gui):  
        self.__gui = gui  


    def run(self):  
        print ('Hello world!')

so that __init__() and run() are methods of your Hello class, not global functions. Otherwise your code works nicely.

And please remember that the latest version of Jython is 2.7.1 - it is not Python3 compatible.

Upvotes: 1

Related Questions