How to use jar files without package information?

旧巷老猫 提交于 2019-12-10 14:16:53

问题


I have a jar called "MyTools". The jar is in c:\data folder. I created a new file in the same folder called "UseTools.java". Now I would like to use some of the classes from the MyTools.jar in my UseTools.java. I tried this but it doesnt seem to work:

import MyTools.*;    
public class UseTools
{
  public static void main(String[] args) 
  {
    MyTools.SomeClass foo = new SomeClass();
    SomeClass.doSomething();
  }
}

I tried to compile this with:

javac -cp . UseTools.java

and got this error message:

UseTools.java:1: package MyTools does not exist
import MyTools.*;
^
UseTools.java:7: package MyTools does not exist
        MyTools.SomeClass foo = new SomeClass()
                                     ^
2 errors

I did not set the package name in any class.

Do I have to set a package name in my jar classes?


回答1:


To mention something that relates more to the title of the question: In Java, you can't access classes in the default package from code within a named package.

This means, if the classes in your jar file do not belong explicitly to any package and inside the jar your files are directly in the root folder without subfolders, they are in the default package. This is not very elaborated and lacks modularity as well as extensibility, but is technically alright. Then, you can only use these classes from code which also is in the default package. But this does not necessarily mean it has to be in the same jar. If you have multiple src or class folders they could all contain classes in the default package which can interact. The organization in JAR files and the package structure in your project are independent of each other.

However, I'd strictly encourage you to use explicit package information.




回答2:


In your MyTools.jar there should be a package with the name MyTools. And before compiling you should add the jar to the classpath.




回答3:


You need to add -cp file.jar instead of -cp .

The latter one will pick up .class files only. BTW: why not using an IDE like netbeans, eclipse or intelliJ?



来源:https://stackoverflow.com/questions/2320092/how-to-use-jar-files-without-package-information

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