开发者

Accessing static java methods in Python through jython

I am currently trying to access a static class in java, within python. I import as normal, then I try to get the class instance of the java class.

from com.exmaple.util import Foo

Foo. __class___.run_static_method()

This doesn't seem to work. suggestions? What am i doing wro开发者_JS百科ng.


Try using

Foo.run_static_method()


I suppose you create an instance of the class and just call the method on that.

from com.example.util import Foo

foo = Foo()
foo.run_static_method()

Assuming just doing Foo.run_static_method() doesn't work.


It works like this example:

Jython 2.5.1 (Release_2_5_1:6813, Sep 26 2009, 13:47:54) 
[Java HotSpot(TM) Client VM (Sun Microsystems Inc.)] on java1.6.0_22
Type "help", "copyright", "credits" or "license" for more information.
>>> import java.lang
>>> java.lang.System.getProperty('user.dir')
u'/home/vinay'

Note that getProperty is a static method of static class java.lang.System.


I ran into this with a class only holding static methods:

public class foo {
     public static void bar() {
         ...
     }
}

Adding a dummy constructor helped in my case. I guess this is because of pythons nature were classes are actually already objects (there is a long post about metaclasses giving some details about class understanding in python, its worthy a read eventhough it is a different topic), and jython trying to make the class an object before running the function eventhough it is static. I f this would be true that might be a bug report. (I am testing on jython2.5).

update: I don't consider my theroy for thecause to likely since I believe Java has some pure static classes as well. However the solution resolved the issue twice.

with dummy constructor:

public class foo {

     public foo() {}   //!This dummy constructor did the trick for me

     public static void bar() {
         ...
     }

}


I ran into this problem, too. There's a gotcha that the other answerers are unaware of. If the Java class doesn't have the keyword public, then its static methods will not be available to Jython. This is confusing because it's independent of whether the methods themselves are public, and other ways of accessing the not-explicitly-public class work, such as instantiation. In summary, do this:

public class foo {
    public static void bar() { ... }
}

not this:

class foo {
    public static void bar() { ... }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜