Jython won't import user-defined class; ImportError: No module named ******

后端 未结 2 1619
孤城傲影
孤城傲影 2021-01-04 20:07

I\'ve been banging my head against the wall for a couple days now trying to figure this out. I\'ve been starting to play around with Jython for fast prototyping. I\'ve hit w

2条回答
  •  我在风中等你
    2021-01-04 21:06

    jython can't import *.java file you need to compile it to *.class.

    Makefile:

    .PHONY: test_beach
    
    test_beach: test_beach.py beach.jar
        jython -J-classpath beach.jar $<
    
    beach.jar: Beach.class
        jar -cf $@ $<
    
    %.class: %.java
        javac $<
    

    Example

    $ make -k 
    javac Beach.java
    jar -cf beach.jar Beach.class
    jython test_beach.py
    *sys-package-mgr*: processing modified jar, '/path/to/beach.jar'
    Cocoa Beach
    

    Other files

    test_beach.py:

    #!/usr/bin/env jython
    import Beach
    
    beach = Beach("Cocoa Beach","Cocoa Beach")
    print beach.getName()
    

    Beach.java:

    //NOTE: if you declare `package a.b;` here then you should put it in a/b directory
    public class Beach {
    
        private String name;
        private String city;
    
    
        public Beach(String name, String city){
            this.name = name;
            this.city = city;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getCity() {
            return city;
        }
    
        public void setCity(String city) {
            this.city = city;
        }
    
    }
    

提交回复
热议问题