Created
April 29, 2011 06:08
-
-
Save sunng87/947926 to your computer and use it in GitHub Desktop.
Convert a python function to a Java anonymous class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# usage, convert this work method to a Runnable anonymous class | |
# | |
# @anonymous_class(Runnable, 'run') | |
# def work(dummy): | |
# print 'hello world' | |
# | |
# work.run() | |
# | |
import types | |
_classdict = {} | |
def anonymous_class(interface, method_name, *args): | |
interface_name = interface.__name__ | |
nextid = _classdict.get(interface_name, -1)+1 | |
_classdict[interface_name] = nextid | |
pseudo_name = "%s$%d" % (interface_name, nextid) | |
Pseudo = type(pseudo_name, (interface,), {}) | |
def wrapper(func): | |
p = Pseudo(*args) | |
setattr(p, method_name, types.MethodType(func, p)) | |
return p | |
return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
宁姐,description里的anonymous拼错了...