jpype icon indicating copy to clipboard operation
jpype copied to clipboard

How to converts Python None to Java null?

Open everydaysayhello opened this issue 4 years ago • 2 comments

I didn't figure out how to convert Python 'None' to Java 'null', and I didn't find a place in the source code,can you help me?Thank you very much!

everydaysayhello avatar Feb 03 '21 02:02 everydaysayhello

None is converted to null automatically:

>>> import jpype
>>> jpype.startJVM()
>>> jpype.java.util.Objects.isNull(None)
True

Is there something that I've not understood?

pelson avatar Feb 03 '21 05:02 pelson

pelson is correct. As None is automatically converted to Java null there is little need specifically convert it most of the time.

The exception is cases in which you need a "typed" null which has a particular static type in order to resolve a method over load. Assuming you have MyObject.call(String) and MyObject.call(List) overloaded and for some reason null is a valid value. (which is incredibly bad practice)

import java
MyObject.call( java.lang.String@None )  # execute MyObject.call(String) with null
MyObject.call( java.util.List@None ) # execute MyObject.call(List) with null

Generally explicit nulls are unnecessary, but if you do then the casting operator @ can be used.

You may be tempted to just try to define a null handle with

null = java.lang.Object@None

Unfortunately, this null has a type of java.lang.Object so it won't resolve methods as expected.

>>> java.lang.String(null)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: No matching overloads found for constructor java.lang.String(java.lang.Object), options are:
        public java.lang.String(int[],int,int)
        public java.lang.String(byte[],int,int,int)
        public java.lang.String(byte[],int)
        public java.lang.String(byte[],int,int,java.lang.String) throws java.io.UnsupportedEncodingException
        ....

Thrameos avatar Feb 03 '21 19:02 Thrameos