I've been asked to write a jython program that uses some java classes as data, as the whole program will eventually be integrated into a larger java framework.
I'm having trouble understanding how jython treats these java classes. For instance, if I declare a java String, jython won't let me assign anything but a string to it. However, if I declare a Map, jython appears to let me treat it as a python dict, but doesn't impose type constraints on either the key or the value.
It also won't let me reassign a private variable if it's a string, but will if it's the Map.
Here is an example java class:
import java.util.Map;
import java.util.HashMap;
public class Trial {
private String name;
private Map<String, Integer> mydict;
public Trial() {
this.name = "Default";
this.mydict = new HashMap<String,Integer>();
}
public Trial(String name) {
this.name = name;
this.mydict = new HashMap<String,Integer>();
}
public String getName() {
return this.name;
}
public Map<String,Integer> getmydict() {
return this.mydict;
}
}
And here is how the jython interpreter has behaved:
>>> import Trial
>>> x = Trial(123)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Trial(): 1st arg can't be coerced to String
>>> x = Trial("A name")
>>> x.name
u'A name'
>>> x.name = "Another name"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: read-only attr: name
>>> x.mydict["a"] = 1
>>> x.mydict[2] = "b"
>>> x.mydict
{2: b, a: 1}
>>> type(x.mydict)
<type 'java.util.HashMap'>
So name is constrained to be a string, and is read-only after being created, because I didn't write a setter function. But mydict, which should be a HashMap object, appears to be able to hold both Strings and Integers as both keys or values, and can be written to, even though I don't have a setter.
Can anyone explain how the type constraints are held, or how the java/python types are mapped to each other? The only documentation I've been able to find is here and here. Neither of these describes how python dictionaries or java Maps are referenced across the language boundary. Also, what affect does converting of types have on performance? Does each conversion have an overhead?