One solution. You could use some sort of message system, queue, or broker of some sort to serialize/deserialize, or pass messages between python and java. Then create some sort workers/producer/consumers to put work on the queues to be processed in python, or java.

Also consider checking out for inspiration: https://www.py4j.org/

py4j is used heavily by/for pyspark and hadoop type stuff.

To answer your question more immediately.

Example using json-simple.:

import org.apache.commons.io.FileUtils;
import org.json.simple.JSONObject;
 //import org.json.simple.JSONObject;
  

public class TestObject 
{
   private double[] values;
   private int length;
   private int anotherVariable;
   private boolean someBool;
   private String someString;

   //getters, setters

   public String toJSON() {
       JSONObject obj=new JSONObject();
       obj.put("values",new Double(this.values));
       obj.put("length",new Integer(this.length));
       obj.put("bool_val",new Boolean(this.SomeBool));
       obj.put("string_key",this.someString);
       StringWriter out = new StringWriter();
       obj.writeJSONString(out);
       return out.toString();
   }

   public void writeObject(){
          Writer writer = new BufferedWriter(
                              new OutputStreamWriter(
                                  new FileOutputStream("anObject.json"), "utf-8")
                              )
                           )

          writer.write(this.toJSON());
   }

   public static void setObject(){
       values = 100.134;
       length = 12;
       anotherVariable = 15;
       someString = "spam";
   }
 }

And in python:

class DoStuffWithObject(object):
    def __init__(self,obj):
        self.obj = obj
        self.changeObj()
        self.writeObj()

    def changeObj(self):
        self.obj['values'] = 100.134;
        self.obj['length'] = 12;
        self.obj['anotherVariable'] = 15;
        self.obj['someString'] = "spam";

    def writeObj(self):
        ''' write back to file '''
        with open('anObject.json', 'w') as f:
            json.dump(self.obj, f)

    def someOtherMethod(self, s):
       ''' do something else '''
       print('hello {}'.format(s))

import json
with open('anObject.json','r') as f:
    obj = json.loads(f.read())
# print out obj['values'] obj['someBool'] ...
for key in obj:
    print(key, obj[key])

aThing = DoStuffWithObject(obj)
aThing.someOtherMethod('there')

And then in java read back the object. There are solutions that exist implementing this idea (JSON-RPC, XML-RPC, and variants). Depending, you may may also want to consider using something like ( http://docs.mongodb.org/ecosystem/drivers/java/ ) the benefit being that mongo does json.

See:

  • https://spring.io/guides/gs/messaging-reactor/
  • http://spring.io/guides/gs/messaging-rabbitmq/
  • http://spring.io/guides/gs/scheduling-tasks/
  • Celery like Java projects
  • Jedis
  • RabbitMQ
  • ZeroMQ

A more comprehensive list of queues:

  • http://queues.io/

Resources referenced:

  • http://www.oracle.com/technetwork/articles/java/json-1973242.html
  • How do I create a file and write to it in Java?
  • https://code.google.com/p/json-simple/wiki/EncodingExamples
Answer from jmunsch on Stack Overflow
🌐
PyPI
pypi.org › project › javaobj-py3
javaobj-py3 · PyPI
This form of object representation is a standard data interchange format in Java world. The javaobj module exposes an API familiar to users of the standard library marshal, pickle and json modules.
      » pip install javaobj-py3
    
Published   Apr 07, 2024
Version   0.4.4
🌐
Py4j
py4j.org
Welcome to Py4J — Py4J
Py4J enables Python programs running in a Python interpreter to dynamically access Java objects in a Java Virtual Machine. Methods are called as if the Java objects resided in the Python interpreter and Java collections can be accessed through standard Python collection methods.
🌐
Real Python
realpython.com › oop-in-python-vs-java
Object-Oriented Programming in Python vs Java – Real Python
August 16, 2024 - In this step-by-step tutorial, you'll learn about the practical differences in Python vs Java for object-oriented programming. By the end, you'll be able to apply your knowledge to Python, understand how to reinterpret your understanding of Java objects to Python, and use objects in a Pythonic way.
Top answer
1 of 4
6

One solution. You could use some sort of message system, queue, or broker of some sort to serialize/deserialize, or pass messages between python and java. Then create some sort workers/producer/consumers to put work on the queues to be processed in python, or java.

Also consider checking out for inspiration: https://www.py4j.org/

py4j is used heavily by/for pyspark and hadoop type stuff.

To answer your question more immediately.

Example using json-simple.:

import org.apache.commons.io.FileUtils;
import org.json.simple.JSONObject;
 //import org.json.simple.JSONObject;
  

public class TestObject 
{
   private double[] values;
   private int length;
   private int anotherVariable;
   private boolean someBool;
   private String someString;

   //getters, setters

   public String toJSON() {
       JSONObject obj=new JSONObject();
       obj.put("values",new Double(this.values));
       obj.put("length",new Integer(this.length));
       obj.put("bool_val",new Boolean(this.SomeBool));
       obj.put("string_key",this.someString);
       StringWriter out = new StringWriter();
       obj.writeJSONString(out);
       return out.toString();
   }

   public void writeObject(){
          Writer writer = new BufferedWriter(
                              new OutputStreamWriter(
                                  new FileOutputStream("anObject.json"), "utf-8")
                              )
                           )

          writer.write(this.toJSON());
   }

   public static void setObject(){
       values = 100.134;
       length = 12;
       anotherVariable = 15;
       someString = "spam";
   }
 }

And in python:

class DoStuffWithObject(object):
    def __init__(self,obj):
        self.obj = obj
        self.changeObj()
        self.writeObj()

    def changeObj(self):
        self.obj['values'] = 100.134;
        self.obj['length'] = 12;
        self.obj['anotherVariable'] = 15;
        self.obj['someString'] = "spam";

    def writeObj(self):
        ''' write back to file '''
        with open('anObject.json', 'w') as f:
            json.dump(self.obj, f)

    def someOtherMethod(self, s):
       ''' do something else '''
       print('hello {}'.format(s))

import json
with open('anObject.json','r') as f:
    obj = json.loads(f.read())
# print out obj['values'] obj['someBool'] ...
for key in obj:
    print(key, obj[key])

aThing = DoStuffWithObject(obj)
aThing.someOtherMethod('there')

And then in java read back the object. There are solutions that exist implementing this idea (JSON-RPC, XML-RPC, and variants). Depending, you may may also want to consider using something like ( http://docs.mongodb.org/ecosystem/drivers/java/ ) the benefit being that mongo does json.

See:

  • https://spring.io/guides/gs/messaging-reactor/
  • http://spring.io/guides/gs/messaging-rabbitmq/
  • http://spring.io/guides/gs/scheduling-tasks/
  • Celery like Java projects
  • Jedis
  • RabbitMQ
  • ZeroMQ

A more comprehensive list of queues:

  • http://queues.io/

Resources referenced:

  • http://www.oracle.com/technetwork/articles/java/json-1973242.html
  • How do I create a file and write to it in Java?
  • https://code.google.com/p/json-simple/wiki/EncodingExamples
2 of 4
0

Agree with the answer below. I think that the bottom line is that "Python and Java are separate interpreter-environments." You therefore shouldn't expect to transfer "an object" from one to the other. You shouldn't expect to "call methods." But it is reasonable to pass data from one to another, by serializing and de-serializing it through some intermediate data format (e.g. JSON) as you would do with any other program.

In some environments, such as Microsoft Windows, it's possible that a technology like OLE (dot-Net) might be usable to allow environments to be linked-together "actively," where the various systems implement and provide OLE-objects. But I don't have any personal experience with whether, nor how, this might be done.

Therefore, the safest thing to do is to treat them as "records," and to use serialization techniques on both sides. (Or, if you got very adventurous, run (say) Java in a child-thread.) An "adventurous" design could get out-of-hand very quickly, with little return on investment.

🌐
pytz
pythonhosted.org › tasselpy › tutorial › py_java_basics.html
Running Java through Python — TASSELpy 0.21 documentation
In both cases, Java is creating an object that is then passed to a Python wrapper object, meaning that the actual String and Taxon objects instantiated are present in the JVM. The underlying Java objects are instances of javabridge.JB_Object and can be accessed with the o attribute.
🌐
GitHub
github.com › vbuell › python-javaobj
GitHub - vbuell/python-javaobj: python-javaobj is a python library that provides functions for reading of Java objects serialized ObjectOutputStream. · GitHub
python-javaobj is a python library that provides functions for reading and writing (writing is WIP currently) Java objects serialized or will be deserialized by ObjectOutputStream.
Starred by 15 users
Forked by 8 users
Languages   Python 72.4% | Java 27.6%
🌐
GitHub
github.com › m-g-90 › cpyjava
GitHub - m-g-90/cpyjava: python module to use java objects
cpyjava is a python extension/module to enable use of java objects from python (cpython).
Author   m-g-90
Find elsewhere
🌐
Quora
quora.com › How-do-Python-objects-compare-and-contrast-with-Java-objects
How do Python objects compare and contrast with Java objects? - Quora
Python: dynamically typed. Variables are names bound to objects; type checks occur at runtime. Any object can be passed where another is expected as long as it supports required attributes/methods (duck typing). Java: statically typed. Variables have declared compile-time types; the compiler enforces method signatures and inheritance constraints.
🌐
InformIT
informit.com › articles › article.aspx
Comparing Python Object-Oriented Code with Java | | InformIT
Now we run our final Java test with 1,600,000 objects: Student John is 23 years old and is studying Physics Student is old: false Time estimate: 104 · That's 104 seconds for 1,600,000 objects. Let's tabulate the results for comparison. The test results show that the Python code outperforms the Java code by a small margin.
🌐
Ptidej Team Blog
blog.ptidej.net › bridging-the-gap-accessing-java-objects-from-python-and-vice-versa
Mind the Gap: Accessing Java Objects from Python and Vice Versa
May 8, 2024 - While many libraries facilitate interoperability between these languages, they often limit you to “one-way communication”, restricting you to accessing Java classes in Python. With Py4J, Python programs can dynamically interact with Java objects within a JVM and vice versa [1].
🌐
GitHub
github.com › tcalmant › python-javaobj
GitHub - tcalmant/python-javaobj: Extended fork of python-javaobj from http://code.google.com/p/python-javaobj/
This form of object representation is a standard data interchange format in Java world. The javaobj module exposes an API familiar to users of the standard library marshal, pickle and json modules.
Starred by 85 users
Forked by 20 users
Languages   Python 92.3% | Java 7.7% | Python 92.3% | Java 7.7%
🌐
Rose-Hulman Institute of Technology
rose-hulman.edu › class › csse › csse220 › 201130 › Resources › Python_vs_Java.html
Python and Java - Comparisons and Contrasts
# Simple Python program year = 2007 print "Hello World!" print "CSSE 120 changed a lot in %d." % (year) // Simple Java program public class HelloWorld { public static void main(String[] args) { int year = 2007; System.out.println("Hello World!"); System.out.print("CSSE 120 changed a lot in "); System.out.print(year); System.out.print('.'); } }
🌐
Jython
jython.org › jython-old-sites › archive › 21 › docs › usejava.html
Accessing Java from Jython
One of the goals of Jython is to make it as simple as possible to use existing Java libraries from Python. Example · The following example of an interactive session with Jython shows how a user could create an instance of the Java random number class (found in java.util.Random) and then interact ...
🌐
Google Groups
groups.google.com › g › jep-project › c › rsVsk8Vdoc0
Passing a Python Object/Function to Java and call
July 9, 2018 - jep.JepException: <class 'TypeError'>: Error converting parameter 1: Expected jep.python.PyObject but received a Sample. ... Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message ... Passing around PyObjects is not supported well on Jep 3.7. Using PyObjects in Java was significantly improved in 3.8.
🌐
Readthedocs
jython.readthedocs.io › en › latest › JythonAndJavaIntegration
Chapter 10: Jython and Java Integration — Definitive Guide to Jython latest documentation
The third piece of code in the example above plays the most important role in the game, this is the object factory that will coerce our Jython code into a resulting Java class. In the constructor, a new instance of the PythonInterpreter is created which we then utilize the interpreter to obtain a reference to our Jython object and stores it into our PyObject.
🌐
Real Python
realpython.com › courses › python-vs-java-object-oriented-programming
Python vs Java: Object Oriented Programming – Real Python
January 25, 2023 - This course compares and contrasts object-oriented programming support in Python vs Java.
🌐
W3Schools
w3schools.com › python › python_classes.asp
Python Classes/Objects
Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.