scijava / script-editor

Script Editor and Interpreter for SciJava script languages
http://imagej.net/Script_Editor
BSD 2-Clause "Simplified" License
12 stars 12 forks source link

getBoolean from PrefService does not work in Jython #19

Closed LauLauThom closed 6 years ago

LauLauThom commented 6 years ago

This was pointed on the forum by @imagejan

#@ PrefService prefs

retrievedValue = prefs.getBoolean(None, "persistedBool", False)
retrievedString = prefs.get(None, "persistedString", "abcdefghijklmnopqrstuvwxyz")

print retrievedValue # always prints False
print retrievedString

prefs.put(None, "persistedBool", not retrievedValue)
prefs.put(None, "persistedString", retrievedString[0:-1])

While it works with getInt

#@ PrefService prefs

retrievedValue = prefs.getInt(None, "persistedBool", False) # <-- see change here
retrievedString = prefs.get(None, "persistedString", "abcdefghijklmnopqrstuvwxyz")

print retrievedValue # now it works as expected
print retrievedString

prefs.put(None, "persistedBool", not retrievedValue)
prefs.put(None, "persistedString", retrievedString[0:-1])
imagejan commented 6 years ago

That's a Python/Jython limitation. True and False are simply 1 and 0 in Java, and will therefore be treated as ints when trying to match overloaded Java methods.

The only solution I see would be to rename the put methods in PrefService to putBoolean and putInt to avoid overloading altogether. But that's only one of many places where overloaded methods are used, and Jython simply doesn't play well with them...

ctrueden commented 6 years ago

See jython issue #1781. There is a workaround given there:

from java.lang import Boolean
prefs.put(None, "persistedBool", Boolean(not retrievedValue))

And maybe some day, this will be fixed in Jython 3.x.