Skip to content

Instantly share code, notes, and snippets.

@sunng87
Created April 29, 2011 06:08
Show Gist options
  • Save sunng87/947926 to your computer and use it in GitHub Desktop.
Save sunng87/947926 to your computer and use it in GitHub Desktop.
Convert a python function to a Java anonymous class
#
# 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
@yuewangny
Copy link

宁姐,description里的anonymous拼错了...

@sunng87
Copy link
Author

sunng87 commented May 4, 2011

@pipitu
没有拼写检查的上辈子都是用Windows的

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment