Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art
Sharing Java Classes from Another Eclipse ProjectBack to Android Cookbook Home | Up to Chapter: Getting Started

Author: Ian Darwin ('idarwin')
In Published Edition? Yes
FormatLanguage: WikiFormat

Sharing Java Classes from Another Eclipse Project


You want to use a class from another project, but don't want to copy-and-paste


Add the project as a "referenced project", and Eclipse (and DEX) will do the work.


You often need to re-use classes from another project. In JPSTrack GPS tracking program, the Android version borrows classes like the file I/O module from the Java SE version. You surely do not want to copy and paste classes willy-nilly from one project into another, because this makes maintenance improbable.

In the simplest case, when the library project contains the source of the classes you want to import, all you have to do is declare the project containing the needed classes (the Java SE version in this case) as a referenced project on the build path. Select Project->Properties->Build Path, select Project, and click "Add". In the screenshot I am adding the SE project "jpstrack" as a dependency on the Android version project "jpstrack.android".

A newer method that is often more reliable, and is now the offically-recommended way, but is only useful if both projects are Android projects, is to declare the library one as a library project, under "Project->Properties>Android>Library Tab", and use the Add button on the other project on the same screen to list the library project as a dependency on the main project. This is now the preferred method.

For the command-line fans, the first method involves editing the .classpath file, while the second method simply creates entries in the project.properties file, for example:

# Project target

Since you are probably keeping both projects under source control (if these are programs you ever ship, you should!), remember to tag both projects when you release the Android project - one of the points in favor of source control is that you need to be able to re-create exactly what you shipped.

See Also

See the official documentation on Library Projects.