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 fork intends to work both on Python 2.7 and Python 3.4+. Since version 0.4.0, two implementations of the parser are available: v1: the classic implementation of javaobj, with a work in progress implementation of a writer. v2: the new implementation, which is a port of the Java project jdeserialize, with support of the object transformer (with a new API) and of the numpy arrays loading.
      » pip install javaobj-py3
    
Published   Apr 07, 2024
Version   0.4.4
🌐
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 of Java objects serialized ObjectOutputStream. - vbuell/python-javaobj
Starred by 15 users
Forked by 8 users
Languages   Python 72.4% | Java 27.6%
🌐
Stack Overflow
stackoverflow.com › questions › 59874329 › reading-java-source-file-with-python
Reading .java source file with Python - Stack Overflow
January 23, 2020 - name = filedialog.askopenfile(initialdir="D:/", filetypes=(("Java Source File", "*.java"), ("All Files", "*.*")), title="Choose a file") print(name) f = open(name, "r") print(f.read()) The content of name is: <_io.TextIOWrapper name='D:/test.java' mode='r' encoding='cp1250'> The exception: TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper · python ·
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.
🌐
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.
🌐
Readthedocs
jpy.readthedocs.io › en › latest › intro.html
Introduction — jpy 0.9.0 documentation
Java programs with jpy.jar on the classpath can import Python modules, access module attributes such as class types and variables, and call any callable objects such as module-level functions, class constructors, as well as static and instance class methods.
🌐
GitHub
github.com › obriencj › python-javatools
GitHub - obriencj/python-javatools: Tools for examining Java bytecode in Python
A python module for unpacking and inspecting Java Class files, JARs, and collections of either.
Starred by 105 users
Forked by 30 users
Languages   Python 96.8% | Shell 1.1% | Makefile 1.0% | Java 0.6% | CSS 0.3% | Emacs Lisp 0.2% | Python 96.8% | Shell 1.1% | Makefile 1.0% | Java 0.6% | CSS 0.3% | Emacs Lisp 0.2%
Find elsewhere
🌐
Experts Exchange
experts-exchange.com › questions › 28586800 › Is-it-possible-to-serialize-an-object-in-Python-so-it-can-be-read-in-Java.html
Solved: Is it possible to serialize an object in Python so it can be read in Java? | Experts Exchange
December 25, 2014 - Hello, I was wondering if it was possible to serialize a Python dictionary, so that it can be read in as a HashMap object in Java? I'm a little skeptical, but I've seen Python do some amazing things...
🌐
pytz
pythonhosted.org › javabridge › java2python.html
Calling Python from Java — python-javabridge 1.0.12 documentation
You can retrieve values by passing a container object such as an array or map as one of the locals and you can set elements in the object with values to be returned. ... class MyClass { static final CPython cpython = CPython(); public List<String> whereIsWaldo(String root) { ArrayList<String> ...
🌐
Jython
jython.org
Home | Jython
import org.python.util.PythonInterpreter; public class JythonHelloWorld { public static void main(String[] args) { try(PythonInterpreter pyInterp = new PythonInterpreter()) { pyInterp.exec("print('Hello Python World!')"); } } } from java.lang import System # Java import print('Running on Java version: ' + System.getProperty('java.version')) print('Unix time from Java: ' + str(System.currentTimeMillis())) Ready to get started?
🌐
GitHub
github.com › vbuell › python-javaobj › issues › 1
Deserialized Java Objects from socket python · Issue #1 · vbuell/python-javaobj
March 21, 2015 - What is the expected output? What do you see instead? The output that I expect is deserialize java object that is serialized by Java ObjectOutputStream and read from the socket by socket python method. recv I see this error: No handlers ...
🌐
STEP Forum
forum.step.esa.int › development › python
Print content of the java.lang.string class objects in python - python - STEP Forum
November 15, 2018 - Hallo, I’m very new to prorgamming ... in Python and I never did anything with Java. However, I started to play with the example code to discover snappy., mostly by reading and printing each statement, and discover what it gives out. What I came across is that if I print some specified objects to get their ...
🌐
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 ...
🌐
Stack Overflow
stackoverflow.com › questions › 48227571 › python3-how-to-run-java-class-file-from-python
Python3: how to run java class file from python - Stack Overflow
January 12, 2018 - "ok" : "no")); } public static String insertLength(Object obj){ String line = obj.toString()); return String.format("[%d]> %s", line.length(), line)); } public static void main(String[] args){ (new ClassWithTest()).testAll()); } } i do not know why this not work?!! i read jython, but i can not use jython, because i did not understand well. could you help me: 1- how can i run java class from python 2- save the out put of execution in text file 3- save the possible error messages in another text file and then terminate.
🌐
Readthedocs
jython.readthedocs.io › en › latest › JythonAndJavaIntegration
Chapter 10: Jython and Java Integration — Definitive Guide to Jython latest documentation
Once the PythonInterpreter has obtained the object and stored it into a PyObject, it’s __call__() method is invoked without any parameters. This will retrieve an empty object that is then stored into another PyObject that is referenced by newObj. Lastly, our newly obtained object is coerced into Java code by calling the __tojava__() method which takes the fully qualified name of the Java interface we’ve implemented with our Jython object.