Released · improving
Java guide · 4/6
As a program grows you need to split it up, pull in third-party libraries, and produce something you can ship. In Java, packages organize classes, Maven or Gradle handle builds and dependencies, the module system can enforce stricter boundaries when you want them, and the usual deliverable is a JAR file.
A package is a namespace for classes. Declare it with package at the top of the file and keep the directory structure in sync with the package name. To avoid collisions, the convention is to start with a reversed domain name you control, such as com.example.
// src/main/java/com/example/shop/order/OrderService.java
package com.example.shop.order;
import java.time.LocalDate;
import java.util.List;
import com.example.shop.product.Product;
import static java.lang.Math.max; // static import
public class OrderService {
public int totalQuantity(List<Product> products) {
int total = 0;
for (Product p : products) total += max(0, p.quantity());
return total;
}
public LocalDate today() {
return LocalDate.now();
}
}Classes in java.lang (String, Math, Integer, and friends) are imported automatically. You can import a whole package with import java.util.*;, but many teams prefer explicit single-type imports so it is obvious where each name comes from. Classes and members declared without an access modifier are visible only within their own package.
Maven describes the project, its dependencies, and its plugins in a single pom.xml. Each dependency is identified by three coordinates (group ID, artifact ID, and version) and is downloaded automatically from a repository such as Maven Central.
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>shop</artifactId>
<version>1.0.0-SNAPSHOT</version>
<properties>
<maven.compiler.release>21</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
</dependencies>
</project>Set maven.compiler.release to the Java release you target (replace the 21 with whatever LTS your team uses), and define properties like ${gson.version} with the current version listed on Maven Central. The commands you will run most often:
mvn compile # compile main sources
mvn test # run the tests
mvn package # build a JAR into target/
mvn dependency:tree # show the resolved dependency treeGradle builds are configured with a Kotlin or Groovy script. Projects normally check in the Gradle wrapper (gradlew), so everyone builds with the same Gradle version without installing it separately.
// build.gradle.kts
plugins {
application
}
repositories {
mavenCentral()
}
dependencies {
implementation("com.google.code.gson:gson:<version>")
testImplementation(platform("org.junit:junit-bom:<version>"))
testImplementation("org.junit.jupiter:junit-jupiter")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
java {
toolchain { languageVersion = JavaLanguageVersion.of(21) }
}
application {
mainClass = "com.example.shop.App"
}
tasks.test { useJUnitPlatform() }implementation dependencies are available at compile time and runtime, while testImplementation ones are visible only to tests. ./gradlew build compiles, tests, and packages in one go, and ./gradlew run launches the configured mainClass. To scaffold a fresh project, run gradle init.
Packages alone cannot stop other code from reaching into your internals. The Java Platform Module System (JPMS) adds a module-info.java file that states what a module depends on (requires) and which packages it makes available (exports). A package that is not exported is off limits to other modules, even if its classes are public.
// src/main/java/module-info.java
module com.example.shop {
requires java.net.http; // a JDK module
requires com.google.gson; // a library module
exports com.example.shop.api; // the public API
opens com.example.shop.model to com.google.gson; // allow reflection
}opens grants reflective access, which serialization libraries need in order to read private fields. Modules are optional: without a module-info.java, your code runs on the classpath just as it always has. Many applications start without modules and adopt them later, typically when publishing a library or building a trimmed runtime image with jlink.
A JAR is a ZIP archive of compiled classes and resources. If its manifest names a Main-Class, you can start it with java -jar. Here is how to build one by hand without a build tool:
javac -d out $(find src/main/java -name "*.java")
jar --create --file app.jar --main-class com.example.shop.App -C out .
java -jar app.jarA plain JAR does not include your third-party dependencies. Either put them on the classpath at launch, for example java -cp "app.jar:libs/*" com.example.shop.App (use ; as the separator on Windows), or let your build produce a distribution that bundles them, such as a shaded JAR from the Maven Shade plugin or Gradle's installDist output.
import to reference classes from other packages.pom.xml; Gradle uses build.gradle.kts. Both fetch dependencies for you.module-info.java uses requires and exports to make module boundaries explicit.java -jar, and decide how dependencies travel with it.
0 comments
Sign in · Sign in to leave a comment.
Be the first to comment.