jpype-project / jpype

JPype is cross language bridge to allow Python programs full access to Java class libraries.
http://www.jpype.org
Apache License 2.0
1.12k stars 183 forks source link

How to construct an instance of a class imported via JClass? #1037

Closed NicolasRouquette closed 2 years ago

NicolasRouquette commented 2 years ago

Since there are two ways to import a Java class, the doc should describe how to create corresponding instances from them.

1st approach (requires Java9 module in the jar):

from org.pkg import MyClass as MyClass1

2nd approach:

MyClass2 = JClass("org.pkg.MyClass")

How do we create an instance of such a class?

1st approach (per the quickguide):

myObject1 = MyClass1()

2nd approach:

I tried this without success:

myObject2 = MyClass2.getConstructor().newInstance()

This fails with an error like this:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [24], in <cell line: 1>()
----> 1 MyClass2.getConstructor()

AttributeError: type object 'org.pkg.MyClass' has no attribute 'getConstructor'
Thrameos commented 2 years ago

As you can see in the quickstart guide, call a class as a function to construct an object.

java::
    public MyClass(int i) {...}

python::
    MyClass = jpype.JClass("MyClass")
    instance = MyClass(1)

https://jpype.readthedocs.io/en/latest/quickguide.html

NicolasRouquette commented 2 years ago

Thanks for the quick reply!

Thrameos commented 2 years ago

Okay I see your confusion. It does not matter how a class is created, all methods allow constructors to be called as functions.

You can use an import.

   from com.mypackage import MyClass

Or you may call JClass directly.

   MyClass = JClass("com.mypackage.MyClass

Or use JPackage

   MyClass = JPackage("com.mypackage").MyClass

It is possible to access reflection methods but those require the "class" rather than the class wrapper. I do not generally recommend it, but you should be able to do something like...

    MyClass.class_.getConstructor()