开发者

How to use jar files without package information?

开发者 https://www.devze.com 2022-12-20 20:50 出处:网络
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开发者

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?


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.


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


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消