Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
NicolasRouquette opened this issue Mar 15, 2022 · 3 comments
Closed

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

NicolasRouquette opened this issue Mar 15, 2022 · 3 comments

Comments

@NicolasRouquette
Copy link

NicolasRouquette commented Mar 15, 2022

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
Copy link
Contributor

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
Copy link
Author

Thanks for the quick reply!

@Thrameos
Copy link
Contributor

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()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants