如何在没有包信息的情况下使用jar文件? [英] How to use jar files without package information?

查看:134
本文介绍了如何在没有包信息的情况下使用jar文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个叫做MyTools的罐子。 jar位于c:\ data文件夹中。我在名为UseTools.java的同一文件夹中创建了一个新文件。现在我想在UseTools.java中使用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

并收到以下错误消息:

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.

我是否必须在jar类中设置包名?

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

推荐答案

提及与问题标题更相关的内容:
在Java中,您无法从命名包中的代码访问默认包中的类。

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.

这意味着,如果jar文件中的类不是显式属于任何包,并且jar中的文件直接位于没有子文件夹的根文件夹中,则它们位于默认包中。这不是很精细,缺乏模块性和可扩展性,但技术上还不错。
然后,您只能使用默认包中的代码中的这些类。但这并不一定意味着它必须在同一个罐子里。如果你有多个src或类文件夹,它们都可以包含默认包中可以交互的类。 JAR文件中的组织和项目中的包结构是相互独立的。

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.

这篇关于如何在没有包信息的情况下使用jar文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆