简体   繁体   English

如何使用 Eclipse 创建 Java 库?

[英]How do I make a Java library with Eclipse?

I'm fairly new to Java and Android programming in general but I would like to create a small Java library for sharing some code between an ordinary (non-Android) Java application and an Android application;一般来说,我对 Java 和 Android 编程还比较陌生,但我想创建一个小型 Java 库,用于在普通(非 Android)Java 应用程序和 Android 应用程序之间共享一些代码; so my question is what is the best way of creating an ordinary Java library with Eclipse?所以我的问题是用 Eclipse 创建普通 Java 库的最佳方法是什么?

I didn't find anywhere the option for creating a new Java library project from Eclipse;我在任何地方都找不到从 Eclipse 创建新 Java 库项目的选项; does this mean that I must use an ordinary Java application as my starting point?这是否意味着我必须使用普通的 Java 应用程序作为起点? As this will be used for an ordinary Java application as well, I cannot use an Android library.因为这也将用于普通的 Java 应用程序,所以我不能使用 Android 库。

Also, what would be the options that I must set up?另外,我必须设置哪些选项?

Finally, as this library will be in the same workspace as the application projects, is it still mandatory to create a JAR file if I can establish a direct link to the library project?最后,由于这个库将与应用程序项目位于同一工作区,如果我可以建立到库项目的直接链接,是否仍然必须创建 JAR 文件?

You don't have to create any library, if you use the same workspace.如果您使用相同的工作区,则不必创建任何库。

Option 1: Just use the source选项 1:仅使用源

In the properties of the project which has the dependencies you can add another source-folder:在具有依赖项的项目的属性中,您可以添加另一个源文件夹:

Properties > Java Build Path > Tab: Source > Add Folder...属性 > Java 构建路径 > 选项卡:源 > 添加文件夹...

In the Project Tab you can "add" the whole project to the other project, too.在“项目”选项卡中,您也可以将整个项目“添加”到另一个项目。 There are many ways to achieve your goal.有很多方法可以实现您的目标。

Option 2: Create and add the library to the Build-Path选项 2:创建库并将其添加到构建路径

Adding an existing Jar (your own library):添加现有的 Jar(您自己的库):

If it is in the workspace:如果它在工作区中:

Properties > Java Build Path > Tab: Libraries > Add JARs...属性 > Java 构建路径 > 选项卡:库 > 添加 JAR...

If it is somewhere on the drive:如果它在驱动器上的某个地方:

Properties > Java Build Path > Tab: Libraries > Add External JARs...属性 > Java 构建路径 > 选项卡:库 > 添加外部 JAR...

Exporting a source folder as a library:将源文件夹导出为库:

Context Menu of Source Folder > Export > Jar File源文件夹的上下文菜单 > 导出 > Jar 文件

There are two types: Executable Jars and "normal" Jars.有两种类型:可执行 Jar 和“普通”Jar。 You don't need an executable Jar.您不需要可执行 Jar。

A Java library is basically a set of JAR files. Java 库基本上是一组 JAR 文件。 So what you can do is generate a JAR based on your source code and add it as a external JAR to the Java build path of your Android and non-Android projects.因此,您可以做的是根据您的源代码生成一个 JAR,并将其作为外部 JAR 添加到您的 Android 和非 Android 项目的 Java 构建路径中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM