Skip to content

Instantly share code, notes, and snippets.

@jimbaker
Created October 15, 2013 00:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimbaker/6984552 to your computer and use it in GitHub Desktop.
Save jimbaker/6984552 to your computer and use it in GitHub Desktop.
Outline of dynamic proxy support for Jython
class DynamicProxy extends InvocationHandler {
protected PyObject __proxy;
protected transient PySystemState __systemState;
public void _setPyInstance(final PyObject _proxy) {
this.__proxy = _proxy;
}
public PyObject _getPyInstance() {
return this.__proxy;
}
public void _setPySystemState(final PySystemState _systemState) {
this.__systemState = _systemState;
}
public PySystemState _getPySystemState() {
return this.__systemState;
}
// ONLY TRICKY PART
// need to register dyamic proxy with the corresponding Python module AND class, using weak mapping
// so that we come through this method, we know this proxy is registered accordingly;
// captured in lookup method used here, to be defined
public void __initProxy__(final Object[] array) {
PyType cls = lookup(this);
Py.initProxy((PyProxy)this, Py.tojava(cls.getModule(), java.lang.String.class), cls.getName(), array);
}
public DynamicProxy() {
__initProxy__(Py.EmptyObjects);
}
public Object invoke(Object proxy, Method method, Object[] args) {
String methodName = method.getName()
if (methodName.equals("_setPyInstance")) { _setPyInstance((PyObject)args[0]); return null; }
if (methodName.equals("_getPyInstance")) { return _getPyInstance(); }
if (methodName.equals("_setPySystemState")) { _setPySystemState((PySystemState)args[0]); return null; }
if (methodName.equals("_getPySystemState")) { return _getPySystemState(); }
final PyObject obj = ProxyMaker.findPython((PyProxy)proxy, methodName);
if (obj != null) {
try {
return Py.tojava(obj._jcallexc(args), method.getReturnType());
} catch (Throwable t) {
obj._jthrow(t);
}
}
return null;
}
public static void classDictInit(final PyObject pyObject) {
// anything else?
pyObject.__setitem__("__supernames__", Py.java2py((Object)new String[] { "clone", "finalize" }));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment