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

后端 未结 2 1594
孤城傲影
孤城傲影 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 20:47

    I think there may be an error in that example. When you import X in Jython, this looks for a Java package named X, not for a class named X.

    Try:

    // Beach.java
    package com.stackoverflow.beach;
    
    public class Beach {
        private String name;
        ...
    

    and in Jython:

    from com.stackoverflow.beach import Beach
    bondi = Beach("Bondi Beach", "Sydney")
    

    edit: Also, you might want to make sure that the full name of the .jar file -- and not just the directory where it resides -- is listed on the CLASSPATH. This is certainly necessary in Java, and I assume Jython's rules are the same in this regard.

    0 讨论(0)
  • 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;
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题