Importing java classes text editor

不羁的心 提交于 2019-12-25 16:35:52

问题


Recently I started using a text editor (text mate) instead of eclipse to program in Java. I hava file1.java in a folder A(/Users/kevincastro/Documents/Code/estructuras/clases) and a file2.java in folder B(/Users/kevincastro/Documents/Code/estructuras/datastructures). I want to import file2.java to file1.java but it doesn't word. I've tried :

import Users.kevincastro.Documents.Code.estructuras.datastructures.*; import datastructures.*; import Documents.Code.estructuras.datastructures.*;

none of them work. I get this error "package Users.kevincastro.Documents.Code.estructuras.datastructures does not exist"

Any help? Thanks


回答1:


It looks like there is a serious misunderstanding here. You seem to think that the import statement actually "import files" or something like that. It doesn't do anything of the sort. The import statement only exists so that you don't have to write the fully qualified name of a class every time you use it. Take the following code :

package a
import b.Bar

public class Foo {
    private Bar bar = new Bar();
    public static void main(String [] args) {
        System.out.println(bar);
    }
}

It is exactly the same as writing :

package a

public class Foo {
    private b.Bar bar = new b.Bar();
    public static void main(String [] args) {
        System.out.println(bar);
    }
}

But it doesn't say much about the location of the file where b.Bar is located! So there is no file to import in your text editor or in your source code. The only thing you know is that b.Bar must be in a folder named b - but that folder can be anywhere.

  1. When you compile a.Foo, javac (the compiler) must either compile b.Bar at the same time, or have access to b.Bar in the classpath. Let's say that you sources are in /SomeDir/src/a/Foo.java and /SomeDir/src/b/Bar.java, and that you compile to /SomeDir/target. Examples :

    • Compile both classes at once (in fact, all java source files in /SomeDir/src): javac -d /SomeDir/target /SomeDir/src/**/*.java

    • Compile Foo, referencing Bar (already compiled to /SomeOtherDir/b/Bar.class): javac -d /SomeDir/target -classpath /SomeOtherDir /SomeDir/src/a/Foo.java

    • Or Bar.class could be in a jar file, etc.

  2. When you run Foo, Bar must be in the classpath, so that it can be found by the classloader. If you want to run /SomeDir/a/Foo.class, and Bar is in /SomeOtherDir/b/Bar.class: java -classpath "/SomeDir:/SomeOtherDir" a.Foo

  3. Once you have tested all that, you should be ready to fall in love with modern build tools such as Maven or Gradle, which will make your life much easier.



来源:https://stackoverflow.com/questions/25694544/importing-java-classes-text-editor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!