Dynamic method invocation

Diez B. Roggisch deets at nospam.web.de
Tue Jun 23 15:51:53 EDT 2009


jythonuser schrieb:
> Hi
> I am new to jythong and was wondering if/how I can do the following -
> 
> a) register a java object with a given name with jython interpreter
> using set method
> b) call methods on the java object - but the methods may not exist on
> the object, so I would like to call from jython a generic method that
> I have defined on the object as opposed to using java reflection.
> Thus the java class is more like a proxy for invocation.
> 
> As an example, I register an instance of java class Bar with name
> foo.  I want to be able to call from jython -
> foo.method1 (args)
> I don't want to define all the methods that I can call from jython on
> class foo but have a generic method that the above jython code will
> invoke.  I want to use a model where the methods that can be called on
> foo are discovered dynamically once they are invoked on java class.
> Clearly Java won't let me do this during method invocation so I am
> wondering if I can register some sort of proxy object with jython that
> will let me then delegate right call down to the java object.

It's very unclear to me what you want, but to me, it looks as if you 
have some misconceptions about jython.

There is no "registration" of java-objects. If you have a java-object, 
you can assign it to a name, and simply invoke any method on it 
(internally, that will mean using reflection, but that's below the 
covers for you)

foo = SomeJavaClass()
foo.some_method()

As long as some_method is defined on SomeJavaClass, this will work. And 
there is also no type-information needed, so this will work in Jython, 
but not in java:


---- java ----

class A {
    public void foo() {};
}

class B { // NOT A SUBCLASS OF A!!
    public void foo() {};
}


---- jython ----

if some_condition:
    bar = A()
else:
    bar = B()

bar.foo()



Regarding the "generic method thing", I guess this will work:


foo = SomeJavaObject()

m = getattr(foo, "method_name_that_might_not_be_defined", None)

if m:
    m(argument)


Diez



More information about the Python-list mailing list