bcdev / jpy

A bi-directional Python-Java bridge used to embed Java in CPython or the other way round.
Apache License 2.0
187 stars 37 forks source link

Use 'import' to import Java classes #13

Open forman opened 10 years ago

forman commented 10 years ago

We want to use

from java.io import File

We currently must use

File = jpy.get_class('java.io.File')

Add a new module function 'import' which calls 'get_class' but then creates new modules up the last dot in the class name. E.g. java.io.File will create the module 'java', than create 'io' and add this to 'java' and then add class 'File' to 'io'.

petrushy commented 9 years ago

This would be a very nice feature that makes the python code more clear to read.

Maybe this could be of help: http://xion.org.pl/2012/05/06/hacking-python-imports/

forman commented 9 years ago

Thanks, petrushy. I already did some tests regarding issue #13. The major problem is, that there is no easy and efficient way to enumerate Java packages in order to look up subpackages and classes by reflection. Java classes are looked up in the Java Native Interface by fully qualified class names (package names included).

A Python statement like

from package import classname

must therefore be reinterpreted as

classname = jpy.get_class('package.classname')

by the Python import machinery.

valgur commented 9 years ago

This would be a great feature indeed. Would it perhaps be sufficient to add an import hook that effectively converts imports from jpy sub-packages

from jpy.package import classname

to

classname = jpy.get_class('package.classname')

instead of allowing the Java packages to be imported from directly? This would avoid the need to enumerate all java packages beforehand.

forman commented 9 years ago

Unfortunately I currently have very little time left for jpy. Maybe someone could have a look into

or so and create a (pure Python) spike that allows me to integrate it into into jpy's C-code later.