FrozenHeart
FrozenHeart

Reputation: 20766

How to share common files between several projects in Java

Suppose that I have a common directory that contains general-purpose files like FileUtils.java and ImageUtils.java. Also I have two projects that should use these common files. What is the most Java-way to import them into these projects? Just add path manually to the -classpath option when using javac and java? Build them into one jar file? Or something else?

Upvotes: 1

Views: 951

Answers (3)

GhostCat
GhostCat

Reputation: 140613

Besides the things that have been said; a word of warning: try to slice your projects aka components to be as small as possible.

In other words: before just blindly going forward and pushing all content of your "common" folder into its own project it might be worthwhile to step back and carefully look at

a) the contents of common b) how other projects make use of that source

And theoretically, you match that whole picture with the thing that is called "architecture" (which may or may not exist for your overall "product") to understand where "reality differs from as-it-should-be".

Then, finally, you define one or more projects that cover all (or parts of) your source code in "common"; and then you change your whole infrastructure so that other "dependent" projects do not rely on using your "common" source files but some kind of build artifact.

Upvotes: 1

Ankur Singhal
Ankur Singhal

Reputation: 26077

Just follow simple steps:

1.) Have module say, companyname-commons-util

2.) build to a jar file, companyname-commons-util.jar

3.) Add dependency of this jar into other projects, and just reuse the classes. (maybe maven, gradle or explicitly adding into classpath)

** The same can be reused in other projects as well. Good from maintenance point of view, and keeping project structure intact.

Upvotes: 4

AlBlue
AlBlue

Reputation: 24060

The recommendation would be to create a third project and then use that to generate a JAR file; you can then use that reference in your other projects. If you're using Maven to build them you'd end up with a different module with your common code in place.

Upvotes: 1

Related Questions