Where to put java packages i want to import? [closed]

强颜欢笑 提交于 2019-12-13 11:26:26

问题


So I have a package named com.company.example, and I want to import it in my .class file. Where do I put that com.company.example package? I don't understand "classpath" please do not use it in answers. I have tried import com.company.example.*; but no packages found

Thanks.


回答1:


So I have a package named com.company.example, and I want to import it in my .class file.

You don't import packages into class files. You import packages into Java source code so you can use the classes in them without using the full name of the class. The packages you import don't become part of the class file.

I don't understand "classpath" please do not use it in answers.

Sorry, but the answer to the question is to use the class path (CLASSPATH). The class path is a list of directories where .class and .jar files can be found. When you use a class from a package, the default classloader in the JVM searches the class path to find a .class file (directly, or inside a .jar) that provides the package you imported. (There are other classloaders, but the normal case is the one that searches through the CLASSPATH for .class files.)

So for example: Let's say you want to use the class com.company.example.Foo in your code. You could do this:

com.company.example.Foo foo = new com.company.example.Foo();
foo.doSomething();

...but that's inconvenient, so you do this at the top of your source file:

import com.company.example.Foo;

...and then this in your code:

Foo foo = new Foo();
foo.doSomething();

Either way, your .class file contains your code and does not contain the Foo class you're using.

At runtime, when the JVM sees that you want to use com.company.example.Foo, it will look through the CLASSPATH for .class files (or .jar files containing .class files) to find one that provides com.company.example.Foo. When it does, it uses the class from that file.

Because the classpath is fundamental to useing Java, I recommend reading up on it.



来源:https://stackoverflow.com/questions/23759812/where-to-put-java-packages-i-want-to-import

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