Jason S
Jason S

Reputation: 189836

exposing a Java Map<> in Jython so that its keys are available with Python "dot" operator (attribute access)

We have some Map<String, Object> in Java that I would like to make available into a Jython function. I would like to access the contents via

mymap.foo.bar

rather than

mymap['foo']['bar']

Is there a way to wrap the Map in an object so that it has this behavior in Jython? (e.g. like the __getattr__ method in Python, only implemented in Java)

Upvotes: 1

Views: 875

Answers (1)

Jason S
Jason S

Reputation: 189836

I ended up implementing this:

@Override public PyObject __findattr_ex__(String name) {
    if (this.containsKey(name))
    {
        return Py.java2py(this.get(name));
    }
    else
    {
        throw Py.AttributeError(name);
    }
}    

for an object that extends both Map<String, Object> and PyObject.

Upvotes: 2

Related Questions