You could also use Py4J. There is an example on the frontpage and lots of documentation, but essentially, you just call Java methods from your python code as if they were python methods:

from py4j.java_gateway import JavaGateway
gateway = JavaGateway()                        # connect to the JVM
java_object = gateway.jvm.mypackage.MyClass()  # invoke constructor
other_object = java_object.doThat()
other_object.doThis(1,'abc')
gateway.jvm.java.lang.System.out.println('Hello World!') # call a static method

As opposed to Jython, one part of Py4J runs in the Python VM so it is always "up to date" with the latest version of Python and you can use libraries that do not run well on Jython (e.g., lxml). The other part runs in the Java VM you want to call.

The communication is done through sockets instead of JNI and Py4J has its own protocol (to optimize certain cases, to manage memory, etc.)

Disclaimer: I am the author of Py4J

Answer from Barthelemy on Stack Overflow
🌐
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:
🌐
Real Python
realpython.com › oop-in-python-vs-java
Object-Oriented Programming in Python vs Java – Real Python
August 16, 2024 - In Java, you declare attributes in the class body, outside of any methods, with a definite type. You must define class attributes before they are used: ... In Python, you both declare and define attributes inside the class __init__(), which is the equivalent of Java’s constructor:
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
Convert Java class structures to Python classes - Stack Overflow
We are trying to avoid duplicate code in a project where Java and Python are used together. The majority of the code base is in Java, with Python now being added due to the prevalence in the machine More on stackoverflow.com
🌐 stackoverflow.com
Does python have an equivalent to Java Class.forName()? - Stack Overflow
Is there an equivalent in Python? Thanks for the responses. To answer those who want to know what I'm doing: I want to use a command line argument as the class name, and instantiate it. I'm actually programming in Jython and instantiating Java classes, hence the Java-ness of the question. More on stackoverflow.com
🌐 stackoverflow.com
using python class methods inside java - Stack Overflow
I have three different classes written in python. They contain several methods which I want to use them inside my java program (creating objects from these python classes and use these objects to c... More on stackoverflow.com
🌐 stackoverflow.com
October 3, 2012
🌐
Readthedocs
jpy.readthedocs.io › en › latest › intro.html
Introduction — jpy 0.9.0 documentation
Python programs that import the jpy module can load Java classes, access Java class fields, and call class constructors and methods.
🌐
Py4j
py4j.org
Welcome to Py4J — Py4J
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.
🌐
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.
🌐
W3Schools
w3schools.com › python › python_classes.asp
Python Classes/Objects
class definitions cannot be empty, but if you for some reason have a class definition with no content, put in the pass statement to avoid getting an error. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
Find elsewhere
🌐
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 ...
🌐
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 - This code generates a reference to Java System class and then it invokes the out.println static method with the input ‘Hello world.`This should print ‘Hello world’ to the standard output. ... To use our costumed libraries, we first need to compile our Java code into a Jar file. This is easily done with maven, which can be installed using this command: ... Jar will be located in the target directory. Now, in our Python code, we should add the jar file to our Java classpath as shown below:
🌐
Rose-Hulman Institute of Technology
rose-hulman.edu › class › cs › csse220 › 200910 › Resources › Python_vs_Java.html
Python and Java - Comparisons and Java
# 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 ...
🌐
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!')"); } } }
🌐
Coursera
coursera.org › browse › computer science › software development
Introduction to Programming with Python and Java | Coursera
Category: Pandas (Python Package)Pandas (Python Package) ... Identify core aspects of object-oriented programming and features of the Java language. Use Eclipse for writing and running Java code. Develop programs that use Java collections and apply core object-oriented programming concepts using classes, polymorphism, and method overloading.
Rating: 4.5 ​ - ​ 1.9K votes
🌐
Quora
quora.com › What-is-the-difference-between-classes-in-Python-and-classes-in-Java
What is the difference between classes in Python and classes in Java? - Quora
Answer (1 of 2): The biggest difference is inheritance. Java is single-inheritance while Python allows for multiple inheritance of sorts. A clear example of this popped up in my own work.
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

🌐
Google Groups
groups.google.com › g › jep-project › c › _Anc4jLByGQ
How can I import a custom java class in python?
# 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):
🌐
Python Software Foundation
wiki.python.org › jython › LearningJython
Jython Course Outline - Python Wiki
Import a Python/Jython file containing a class definition. Create an instance of that class. Import a module from the standard Python/Jython library, for example, re or os.path. Use a method from that module. Import a Java class, for example, java.util.Vector.
Top answer
1 of 8
194

Reflection in python is a lot easier and far more flexible than it is in Java.

I recommend reading this tutorial (on archive.org)

There's no direct function (that I know of) which takes a fully qualified class name and returns the class, however you have all the pieces needed to build that, and you can connect them together.

One bit of advice though: don't try to program in Java style when you're in python.

If you can explain what is it that you're trying to do, maybe we can help you find a more pythonic way of doing it.

Here's a function that does what you want:

def get_class( kls ):
    parts = kls.split('.')
    module = ".".join(parts[:-1])
    m = __import__( module )
    for comp in parts[1:]:
        m = getattr(m, comp)            
    return m

You can use the return value of this function as if it were the class itself.

Here's a usage example:

>>> D = get_class("datetime.datetime")
>>> D
<type 'datetime.datetime'>
>>> D.now()
datetime.datetime(2009, 1, 17, 2, 15, 58, 883000)
>>> a = D( 2010, 4, 22 )
>>> a
datetime.datetime(2010, 4, 22, 0, 0)
>>> 

How does that work?

We're using __import__ to import the module that holds the class, which required that we first extract the module name from the fully qualified name. Then we import the module:

m = __import__( module )

In this case, m will only refer to the top level module,

For example, if your class lives in foo.baz module, then m will be the module foo
We can easily obtain a reference to foo.baz using getattr( m, 'baz' )

To get from the top level module to the class, have to recursively use gettatr on the parts of the class name

Say for example, if you class name is foo.baz.bar.Model then we do this:

m = __import__( "foo.baz.bar" ) #m is package foo
m = getattr( m, "baz" ) #m is package baz
m = getattr( m, "bar" ) #m is module bar
m = getattr( m, "Model" ) #m is class Model

This is what's happening in this loop:

for comp in parts[1:]:
    m = getattr(m, comp)    

At the end of the loop, m will be a reference to the class. This means that m is actually the class itslef, you can do for instance:

a = m() #instantiate a new instance of the class    
b = m( arg1, arg2 ) # pass arguments to the constructor

  
2 of 8
31

Assuming the class is in your scope:

globals()'classname'

Otherwise:

getattr(someModule, 'classname')(args, to, constructor)

Edit: Note, you can't give a name like 'foo.bar' to getattr. You'll need to split it by . and call getattr() on each piece left-to-right. This will handle that:

module, rest = 'foo.bar.baz'.split('.', 1)
fooBar = reduce(lambda a, b: getattr(a, b), rest.split('.'), globals()[module])
someVar = fooBar(args, to, constructor)
🌐
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 ...
🌐
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.