So is there any way to generate simple "Pojo" Python classes from Java code?

I had a go at it and below is the solution:

Considering below simplistic Pojo.java

public class Pojo {
    private String string = "default";
    public int integer = 1;
    public String getString(){
        return string;
    }
}

The solution will need 3 phases

1. Java Pojo to JSON Schema

I could find below options:

  1. FasterXML/jackson-module-jsonSchema: This is the base, which below libraries also use internally.
  2. mbknor/mbknor-jackson-jsonSchema: Officially cited by above to support the v4 of the json schema.
  3. reinert/JJSchema

With below relevant code with option 1(also go through the site):

ObjectMapper MAPPER = new ObjectMapper();
JsonSchemaGenerator generator = new JsonSchemaGenerator(MAPPER);
JsonSchema jsonSchema = generator.generateSchema(Pojo.class);
System.out.println(MAPPER.writeValueAsString(jsonSchema));

Below output json schema string is got:

{"type":"object","id":"urn:jsonschema:Pojo","properties":{"string":{"type":"string"},"integer":{"type":"integer"}}}

2. JSON Schema post-process

This phase is required mainly because I found that for the simplistic use case(at least), Step 3 below needs a json schema that has a definitions property mandatorily. I guess this is because of the evolving schema definitions @ http://json-schema.org/. Also, we can include a title property to specify the name of the python class that next step will generate.

We can easily accomplish these in the java program of Step 1 above as a post step. We need a json schema string of below form:

{"definitions": {}, "title": "Pojo", "type":"object","id":"urn:jsonschema:Pojo","properties":{"string":{"type":"string"},"integer":{"type":"integer"}}}

Notice that only addition is "definitions": {}, "title": "Pojo"

3. Json schema to Python class

frx08/jsonschema2popo seems to be doing this job quite nicely.

pip install jsonschema2popo
jsonschema2popo -o /path/to/output_file.py /path/to/json_schema.json

Some more points

  1. The Java-Json schema generators will only include those properties in the output which are either public or have a public getter.
  2. I assume that for a mass migration annotating the Java classes will be a pain. Otherwise, if this is feasible to you, all the above java libraries provide rich annotations where you can specify whether a property is mandatory and much more.
Answer from sujit on Stack Overflow
Top answer
1 of 3
10

So is there any way to generate simple "Pojo" Python classes from Java code?

I had a go at it and below is the solution:

Considering below simplistic Pojo.java

public class Pojo {
    private String string = "default";
    public int integer = 1;
    public String getString(){
        return string;
    }
}

The solution will need 3 phases

1. Java Pojo to JSON Schema

I could find below options:

  1. FasterXML/jackson-module-jsonSchema: This is the base, which below libraries also use internally.
  2. mbknor/mbknor-jackson-jsonSchema: Officially cited by above to support the v4 of the json schema.
  3. reinert/JJSchema

With below relevant code with option 1(also go through the site):

ObjectMapper MAPPER = new ObjectMapper();
JsonSchemaGenerator generator = new JsonSchemaGenerator(MAPPER);
JsonSchema jsonSchema = generator.generateSchema(Pojo.class);
System.out.println(MAPPER.writeValueAsString(jsonSchema));

Below output json schema string is got:

{"type":"object","id":"urn:jsonschema:Pojo","properties":{"string":{"type":"string"},"integer":{"type":"integer"}}}

2. JSON Schema post-process

This phase is required mainly because I found that for the simplistic use case(at least), Step 3 below needs a json schema that has a definitions property mandatorily. I guess this is because of the evolving schema definitions @ http://json-schema.org/. Also, we can include a title property to specify the name of the python class that next step will generate.

We can easily accomplish these in the java program of Step 1 above as a post step. We need a json schema string of below form:

{"definitions": {}, "title": "Pojo", "type":"object","id":"urn:jsonschema:Pojo","properties":{"string":{"type":"string"},"integer":{"type":"integer"}}}

Notice that only addition is "definitions": {}, "title": "Pojo"

3. Json schema to Python class

frx08/jsonschema2popo seems to be doing this job quite nicely.

pip install jsonschema2popo
jsonschema2popo -o /path/to/output_file.py /path/to/json_schema.json

Some more points

  1. The Java-Json schema generators will only include those properties in the output which are either public or have a public getter.
  2. I assume that for a mass migration annotating the Java classes will be a pain. Otherwise, if this is feasible to you, all the above java libraries provide rich annotations where you can specify whether a property is mandatory and much more.
2 of 3
1

TechWalla @https://www.techwalla.com/articles/how-to-convert-java-to-python has detailed instructions. See if it helps you.

Pasting the instructions here Step 1 Download and extract java2python. The file you download is a gzip file, and it contains within it a tarball file; both are compression schemes, and both can be decompressed with 7zip, an open-source program.

Step 2 Place the contents of the java2python folder on the root of your C:\ drive.

Step 3 Open a command prompt and navigate to "C:\java2python\" before typing in "python setup.py install" without quotes. This will tell the Python interpreter to run the setup script and prepare your computer. Change directories to "C:\java2python\bin\" and keep the window open.

Step 4 Copy the Java file to be converted into your bin subfolder, under java2python. In the command line, run "j2py -i input_file.java -o output_file.py," replacing the input_file and output_file with your filenames.

Step 5 Open the new Python folder and read the code. It probably won't be perfect, so you'll need to go over it to make sure it makes sense from a Python point of view. Even spending time manually checking, however, you will have saved large amounts of time from hand-converting

๐ŸŒ
pytz
pythonhosted.org โ€บ tasselpy โ€บ tutorial โ€บ py_java_basics.html
Running Java through Python โ€” TASSELpy 0.21 documentation
Below, I import and instantiate a String from the TASSELpy.java.lang.String.String class and a Taxon from the TASSELpy.net.maizegenetics.taxa.Taxon.Taxon class. >>> from TASSELpy.java.lang.String import String >>> from TASSELpy.net.maizegenetics.taxa.Taxon import Taxon >>> aString = String("I'm a Java String!") >>> aString String('I'm a Java String!') >>> aString.o <Java object at 0x1605c8d0> >>> aTaxon = Taxon("jabberwocky") >>> aTaxon Taxon(jabberwocky) >>> aTaxon.o <Java object at 0x1605c8e8> 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.
Discussions

Calling Java from Python - Stack Overflow
A Python module to access Java classes as Python classes using JNI. More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to convert Java class to Python
Can someone tell me how to convert this java classes to python: Java: class Vertex { double x; double y; double z; Vertex(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } } class Triangle { Vertex v1; Vertex v2; Vertex v3; Color color; Triangle(Vertex v1, Vertex v2, Vertex ... More on forum.inductiveautomation.com
๐ŸŒ forum.inductiveautomation.com
0
0
January 25, 2018
Importing Java class into a python project - Stack Overflow
I've been trying to find a method ... into my python project. I have the jar file in the same path as my project. I want to use it for kmeans clustering, since it allows me to change the distance metric. I am wondering though whether with the implementation that one of you suggest, whether I'll be able to pass a different java class as a parameter ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
how to switch from java to python?
It isn't as hard as you might think. If you know java you know the core fundamentals of coding that are basically the same in every language. Once you know what you need to do, it's basically looking up syntax, libraries, etc. My advice is don't stress about it, take it slow. Python is actually pretty user friendly! More on reddit.com
๐ŸŒ r/learnpython
8
10
April 8, 2024
๐ŸŒ
Py4j
py4j.org
Welcome to Py4J โ€” Py4J
Py4J also enables Java programs to call back Python objects. Py4J is distributed under the BSD license. Here is a brief example of what you can do with Py4J. The following Python program creates a java.util.Random instance from a JVM and calls some of its methods. It also accesses a custom Java class, AdditionApplication to add the generated numbers.
๐ŸŒ
Google Groups
groups.google.com โ€บ g โ€บ jep-project โ€บ c โ€บ _Anc4jLByGQ
How can I import a custom java class in python?
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message ... # importing the java.lang.Class objects from java.lang import Integer from java.util import ArrayList as AL # instantiation x = Integer(5) y = Integer(51) a = AL() I created a very simple python script that instantiates a custom class (test.py):
๐ŸŒ
codecentric
codecentric.de โ€บ en โ€บ knowledge-hub โ€บ blog โ€บ java-classes-python
How to use Java classes in Python
November 15, 2021 - First, during the training, where we will call it directly from Python. And later in production, where we will call it from our Java program to give the trained net a basis for making a decision. Enter JPype ! The import of a Java class โ€” without any changes to the Java sources โ€” can be accomplished simply with the following code:
๐ŸŒ
Better Programming
betterprogramming.pub โ€บ accessing-java-classes-in-python-using-pyjnius-6122bcaad49a
Accessing Java Classes in Python Using Pyjnius | by Eldad Uzman | Better Programming
March 8, 2022 - The main method instantiates the Calculator class with an initial factor being 1 and a step increment of 2, and then the calculateFactoredMean is called three times. ... Now, let's consume this code into a Python application. Pyjnius is based on the Java native interface and reflection to provision Java classes into Python runtime.
Find elsewhere
๐ŸŒ
Jython
jython.org
Home | Jython
The seamless interaction between Python and Java allows developers to freely mix the two languages both during development and in shipping products. 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!')"); } } }
๐ŸŒ
GitHub
github.com โ€บ natural โ€บ java2python
GitHub - natural/java2python: Simple but effective library to translate Java source code to Python. ยท GitHub
#!/usr/bin/env python """ generated source for module HelloWorld """ # This is the HelloWorld class with a single method. class HelloWorld(object): """ generated source for class HelloWorld """ @classmethod def main(cls, args): """ generated source for method main """ print "Hello, world." if __name__ == '__main__': import sys HelloWorld.main(sys.argv)
Starred by 577 users
Forked by 246 users
Languages ย  Python 94.3% | GAP 2.9% | Java 2.7%
๐ŸŒ
Readthedocs
jpy.readthedocs.io โ€บ en โ€บ latest โ€บ intro.html
Introduction โ€” jpy 0.9.0 documentation
With jpy you can implement Java interfaces using Python. We instantiating Java (proxy) objects from Python modules or classes. If you call methods of the resulting Java object, jpy will delegate the calls to the matching Python module functions or class methods.
๐ŸŒ
Javainuse
javainuse.com โ€บ java2py
Online Java to Python Converter Tool
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Online tool to convert Java source code into Python.
๐ŸŒ
Inductive Automation
forum.inductiveautomation.com โ€บ ignition
How to convert Java class to Python - Ignition - Inductive Automation Forum
January 25, 2018 - Can someone tell me how to convert this java classes to python: Java: class Vertex { double x; double y; double z; Vertex(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } } class Triangle { Vertex v1; Vertex v2; Vertex v3; ...
๐ŸŒ
PyPI
pypi.org โ€บ project โ€บ java2python
java2python ยท PyPI
May 3, 2012 - Simple but effective tool to translate Java source code into Python.
      ยป pip install java2python
    
Published ย  May 03, 2012
Version ย  0.5.1
๐ŸŒ
Imagej
py.imagej.net โ€บ en โ€บ latest โ€บ 02-Working-with-Java-classes-and-Python.html
2 Working with Java classes and Python โ€” PyImageJ documentation
For example, to import the java.lang.System class, you could write: from scyjava import jimport System = jimport('java.lang.System') scyjava.jimport is all that is needed to use Java objects/resources in Python. For example importing java.lang.Runtime allows us to inspect the memory available to our Java Virtual Machine (JVM).
๐ŸŒ
GitHub
github.com โ€บ manishpandey0626 โ€บ java-python-converter
GitHub - manishpandey0626/java-python-converter: A Gen AI-powered service that converts partial Java classes into clean, idiomatic Python 3 code using GitHub Copilot and OpenAI models. ยท GitHub
A Gen AI-powered service that converts partial Java classes into clean, idiomatic Python 3 code using GitHub Copilot and OpenAI models. This tool automates the conversion of Java class structures into Python 3 syntax, making it easier to modernize ...
Author ย  manishpandey0626
๐ŸŒ
Real Python
realpython.com โ€บ oop-in-python-vs-java
Object-Oriented Programming in Python vs Java โ€“ Real Python
August 16, 2024 - Java classes are defined in files with the same name as the class. So, you have to save this class in a file named Car.java. Only one class can be defined in each file. A similar small Car class is written in Python as follows:
Top answer
1 of 2
4

In short, you can't run Java code natively in a CPython interpreter.

Firstly, Python is just the name of the specification for the language. If you are using the Python supplied by your operating system (or downloaded from the official Python website), then you are using CPython. CPython does not have the ability to interpret Java code.

However, as you mentioned, there is an implementation of Python for the JVM called Jython. Jython is an implementation of Python that operates on the JVM and therefore can interact with Java modules. However, very few people work with Jython and therefore you will be a bit on your own about making everything work properly. You would not need to re-write your vanilla Python code (since Jython can interpret Python 2.x) but not all libraries (such as numpy) will be supported.

Finally, I think you need to better understand the K-Means algorithm, as the algorithm is implicitly defined in terms of the Euclidean distance. Using any other distance metric would no longer be considered K-Means and may affect the convergence of the algorithm. See here for more information.


Again, you can't run Java code natively in a CPython interpreter. Of course there are various third party libraries that will handle marshalling of data between Java and Python. However, I stand by my statement that for this particular use case you are likely better to use a native Python library (something like K-Medoid in Scikit-Learn). Attempting to call through to Java, with all the associated overhead, is overkill for this problem, in my opinion.

2 of 2
2

To "answer" your question directly, Jython will be your best bet if you simply want to import Java classes. Jython strives very hard to be as compatible with Python 2.x as possible and does a good job. So you won't have to spend too much time rewriting code. Just simply run it with Jython and see what happens, then modify what breaks.

Now for the Python answer :D. You may want to use scikit for a native implementation. It will certainly be faster than running anything in Jython.

Update

I think the Py4J module is what you're looking. It works by running a server in your Java code and the Python code will communicate with the Java server. The only good thing about "Py4J" is that it provides the boiler plate code for you. You can very easily setup your own client/server with no extra modules. However I still don't think it's a superior option compared to Pythons native modules.

References

How to import Java class w/ Jython

Scikit - K-Means

๐ŸŒ
Liacs
rsewiki.liacs.nl โ€บ calling_java_from_python
Calling Java from Python [LIACS Wiki]
April 1, 2021 - A Python module to access Java classes as Python classes using the Java Native Interface (JNI).