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

醉酒当歌 提交于 2020-01-05 11:31:28

问题


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)


回答1:


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.



来源:https://stackoverflow.com/questions/30468876/exposing-a-java-map-in-jython-so-that-its-keys-are-available-with-python-dot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!