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

查看:23
本文介绍了如何使用没有包信息的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();
  }
}

我试图编译它:

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 或 class 文件夹,它们都可以包含可以交互的默认包中的类.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天全站免登陆