[ Updike, Clark ]
> I'm trying to construct an instance of a java object given a
> reference
> to a
> method of a java class. It is simple to do it for a jython class:
>
> >>> from org.python.core import PyMethod, PyReflectedFunction
> >>> def instanceFromMethod(method):
> ... if type(method) == PyMethod:
> ... return method.im_class()
> ... elif type(method) == PyReflectedFunction:
> ... print "Sorry..."
> ... else:
> ... raise Exception("Must be a function or a reflected
> function")
> ...
> >>> class X:
> ... def f(self):
> ... pass
> ...
> >>> instanceFromMethod(X.f)
> <__main__.X instance at 6814979>
> >>>
>
> But I don't know how to do anything similar when it is a java-based
> method:
>
> >>> from java.lang import Object
> >>> instanceFromMethod(Object.toString)
> Sorry...
>
> PyReflectedFunction doesn't seem to expose anything traceable back to
> the original
> class (or proxy thereof). Does anyone have any ideas?
¨
Hi Clark,
only some thoughts, not a real solution.
Your code only works if you have no inheritance:
>>> class X:
... def f(self):
... pass
...
>>> class Y(X):
... def g(self):
... pass
...
>>> Y.f.im_class()
<__main__.X instance at 31248093>
>>>
i suppose you expected an instance of Y here, didn't you ?
If not, you can do the same with PyReflectedFunctions. I have 3
examples below.
1. Method really defined on class itself:
>>> from java.lang import Throwable
>>> Throwable.printStackTrace.argslist[0].declaringClass
<jclass java.lang.Throwable at 27988400>
>>>
2. Method defined by an interface:
>>> from java.lang import Short
>>> Short.byteValue.argslist[0].declaringClass
<jclass java.lang.Number at 32519825>
>>>
3. Method defined by a superclass:
>>> from java.lang import Short
>>> Short.toString.argslist[0].declaringClass
<jclass java.lang.Object at 21573890>
>>>
Best wishes,
Oti.
|