From: <th...@us...> - 2009-11-30 23:27:11
|
Revision: 6952 http://jython.svn.sourceforge.net/jython/?rev=6952&view=rev Author: thobes Date: 2009-11-30 23:27:03 +0000 (Mon, 30 Nov 2009) Log Message: ----------- Added an initial implementation of automatic coercion of function objects to any single method interface. Modified Paths: -------------- trunk/jython/src/org/python/core/PyFunction.java Modified: trunk/jython/src/org/python/core/PyFunction.java =================================================================== --- trunk/jython/src/org/python/core/PyFunction.java 2009-11-29 16:11:42 UTC (rev 6951) +++ trunk/jython/src/org/python/core/PyFunction.java 2009-11-30 23:27:03 UTC (rev 6952) @@ -1,6 +1,10 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; + import org.python.expose.ExposedDelete; import org.python.expose.ExposedGet; import org.python.expose.ExposedMethod; @@ -388,6 +392,24 @@ public String toString() { return String.format("<function %s at %s>", __name__, Py.idstr(this)); } + + @Override + public Object __tojava__(Class<?> c) { + // Automatically coerce to single method interfaces + if (c.isInterface() && c.getDeclaredMethods().length == 1) { + return Proxy.newProxyInstance(c.getClassLoader(), new Class[]{c}, new InvocationHandler() { + // XXX: not the most efficient implementation - the invocation handler could be shared + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + if (args == null || args.length == 0) { + return __call__().__tojava__(method.getReturnType()); + } else { + return __call__(Py.javas2pys(args)).__tojava__(method.getReturnType()); + } + } + }); + } + return super.__tojava__( c ); + } @Override public boolean isMappingType() { return false; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |