【问题标题】:I can't use the custom class after importing the jar file into the eclipse project将jar文件导入eclipse项目后无法使用自定义类
【发布时间】:2014-02-10 18:20:28
【问题描述】:

我创建了一个自定义类。我编写了类代码并将其放入 mycustomclass.class 中。我将 .class 文件放入 Winrar 存档,然后将存档重命名为 mycustomclass.jar。

这是我正在测试的代码,以了解导入自定义类的工作原理。

public class mycustomclass {

int weight;
int height;

public int calculatebmi(int weight, int height){

int bmi = ((weight+height)*(weight+height))/(height*height);
return bmi;

}
}

这个jar文件的文件结构是这样的:

mycustomclass.jar>mycustomclass.class(inside the jar file)

然后我通过单击 java 构建路径下的“添加外部 jar 文件”将 jar 文件添加到项目中。我还选中了 java 构建路径属性的 order and export 列表中 jar 文件名旁边的复选框。当我像这样将类添加到 mainactivity.java 文件时:

import mycustomclass;

上面写着mycustomclass cannot be resolved

jar 文件位于引用的库文件夹下,mycustomclass.class 文件位于“默认包”下,如下所示:

Refereneced Libraries>default package>mycustomclass.class

我认为自定义类文件必须在包层次结构中,因此我在 jar 文件中创建了一个名为 mycustomclassfolder 的文件夹,并将 mycustomclass.class 文件放入其中。

mycustomclass.jar>mycustomclassfolder>mycustomclass.class

然后我就这样做了。

import mycustomclassfolder.mycustomclass;

错误信息:

mycustomclassfolder.mycustomclass cannot be resolved

这是它在项目文件列表中的列出方式:

mycustomclass.jar>mycustomclassfolder>mycustomclass.class

除了将文件导入到项目中之外,我还需要做什么才能使用 import ... 关键字在 mainactivity.java 文件中使用该类?

谢谢。

【问题讨论】:

  • 我不确定 winrar 是否可以生成有效的.jar 文件(jar 本质上是.zip,而不是.rar)。试试jar 工具。
  • 谢谢。我会试试的。
  • 我使用该工具制作 jar,将 jar 文件添加到项目后,我仍然收到相同的错误消息:mycustomclass cannot be resolved to a type。我该怎么做才能完成这项工作?谢谢。

标签: java android eclipse jar


【解决方案1】:

2 个问题:

  1. 您应该使用 JDK 随附的 jar 工具来创建 jar 文件。任何其他工具生成的压缩文件可能与 jar 文件格式不兼容。
  2. 您不能import 默认包中的文件。甚至不需要在默认包中导入类。只需将包含该类的jar文件添加到classpath/build classpath后即可使用该类。

【讨论】:

  • 嗨。我能够使用 jar 工具创建 jar 文件。但它仍然告诉我同样的错误:mycustomclass cannot be resolved to a typeimport mycustomclass;。我可以设置的classpath/build classpath 属性在哪里?所以我什至不必将 jar 文件导入到项目中来做到这一点?如果我在 jar 文件中有文件夹,在这些文件夹中有类文件怎么办?如果是这种情况,我是否必须导入 jar 文件,然后使用 import 关键字访问类?谢谢。
猜你喜欢
  • 2013-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-11
  • 1970-01-01
  • 2012-06-28
  • 1970-01-01
相关资源
最近更新 更多