- Lab
-
Libraries: If you want this lab, consider one of these libraries.
- Core Tech
Java Type Safety Meets Runtime Reality
A regional warehouse network uses an internal toolkit to track shipment crates, consolidate fleets of crates from different depots, and report on which operations are audited. You will finish the toolkit step by step. You will build a bounded generic Crate with inferred types, write wildcard methods that stay usable for callers, and flatten generic varargs without heap pollution. You will also compare array covariance with generic invariance, then use annotation retention and reflection to build an audit trail.
Lab Info
Table of Contents
-
Challenge
Step 1: Tour the warehouse codebase
Welcome to the warehouse toolkit
A regional warehouse network uses an internal toolkit to track shipment crates, merge fleets of crates from different depots, and keep an audit trail of who touched inventory. It was written fast: it leans on raw types in a couple of places, mixes arrays and generics without thinking about it, and logs nothing. Over the next four steps you will harden it, one hazard at a time, until it compiles cleanly and fails loudly only where Java itself genuinely cannot protect you. ## Where things live
The project is a single Maven module under
src/main/java/lab/:Crate.java— the generic holder every other class builds on.Fleet.java— wildcard-based operations that merge and default-fill lists of crates.Loader.java— a generic varargs method with a latent heap-pollution bug.Storage.java— a side-by-side demo of array covariance versus generic invariance.AuditLog.java/Sunset.java— two annotations with different retention policies.Ledger.java— reflection-based auditing built on those annotations.WarehouseApp.java— themainentry point that runs the whole pipeline.
Each file already compiles; the gaps you'll fill are marked
// TODO: Task <n> - ...with a// Hint:line underneath. ## Five hazards, five stepsEach remaining step targets one classic Java type-safety trap:
- Step 2 —
Crate<T>needs a bound so its generic methods can compare contents, and so callers never have to spell out type arguments by hand. - Step 3 —
Fleet's wildcard methods currently either won't compile or hand back a uselessObject; you'll apply PECS (producer-extends, consumer-super) and fix a wildcard-capture problem. - Step 4 —
Loader's varargs method can throwClassCastExceptionat runtime because of type erasure, andStorageshows the same class of failure happening through arrays instead of generics. - Step 5 —
AuditLogandSunsetlook identical in source but behave completely differently at runtime because of one annotation attribute: retention policy.
By the time
WarehouseApp.mainruns at the end, every one of these will be fixed and wired together. -
Challenge
Step 2: Build the bounded generic Crate foundation
Bounded type parameters
Crate<T>needs to compare the crates it holds, but a bareTonly supportsequalsandhashCode, and nothing that expresses "bigger" or "smaller". A bounded type parameter,T extends Comparable<T>, tells the compiler that whateverTturns out to be, it will have acompareTomethod it can call directly, with no casts. That bound is already declared on theCrate<T>class inCrate.java; your job is to put it to use. ## Inference through a factory methodWith
compareContentsworking, the next friction point is construction. Writingnew Crate<Integer>(5)everywhere is noisy, andCrate.<Integer>of(5)is worse. A static generic method with its own type parameter lets the compiler inferTfrom the argument you pass in, soCrate.of(5)alone is enough. This is the same inference mechanism behindList.of(...)and friends in the standard library. ## Reusing the bound in a second static methodBecause the class-level bound guarantees
compareToexists, any generic method operating onCrate<T>values can lean oncompareContentsinstead of re-deriving a comparison from scratch.largerOfis the first place that pays off: it takes two crates and returns whichever one wins the comparison, entirely through methods you've already written. -
Challenge
Step 3: Make wildcard fleet operations usable
PECS: producer-extends
Fleetneeds to total up weights from a list of crates, but callers might hand it aList<Crate<Integer>>, or aList<SpecialCrate>ifSpecialCrateextendsCrate<Integer>. A wildcardList<? extends Crate<Integer>>accepts any of those, because the method only ever reads crates out of the list — it's a producer of values. The mnemonic is PECS: Producer Extends, Consumer Super. ## PECS: consumer-superThe opposite case is filling a list with default crates. Here the method only ever writes into the list, so it should accept the widest possible destination:
List<? super Crate<Integer>>, which is a list ofCrate<Integer>or anything broader, likeList<Object>. Trying to read a specific type back out of a super-wildcard list wouldn't compile, which is exactly the guarantee that makes it safe to write into. ## Wildcard captureSometimes a caller only has
List<? extends Crate<?>>, which is an unknown crate type inside an unknown crate type, and still needs a real, usableCrate<?>back, not justObject. You can't name the wildcard's hidden type inside a method body directly, but a private helper method with its own type parameter<T>can capture it, work with a concreteTinternally, and hand back something callers can actually use. -
Challenge
Step 4: Expose and fix erasure and covariance traps
Type erasure and heap pollution
At runtime,
List<T>becomes plainList, and the type argument is erased. Generic varargs methods (List<T>... lists) build an array of those erased lists, and if a method's body ever writes into that array, it can silently store the wrong type, corrupting the heap in a way the compiler couldn't see. The fix isn't to avoid varargs. It's to only ever read from the varargs array and never assign into it, which is what@SafeVarargspromises the compiler on your behalf. ## Arrays are covariant, generics are notString[]is a subtype ofObject[], which means arrays are covariant: you can store aString[]in anObject[]variable and the compiler is happy. But the array still remembers its real element type at runtime, so storing the wrong type through thatObject[]reference throwsArrayStoreException. Generic lists made the opposite trade-off:List<String>is not a subtype ofList<Object>, so the equivalent mistake is a compile error instead of a runtime crash.Storage.javaputs both side by side. -
Challenge
Step 5: Wire in annotation-driven auditing and finish the app
Retention policy is a design decision
AuditLog.javaandSunset.javaeach declare an annotation, but with different@Retentionvalues.@AuditLogusesRetentionPolicy.RUNTIME, so the JVM keeps it in memory and reflection can see it on a loaded class.Ledger.javauses that to build an audit trail: scanning a class's declared methods and picking out the ones marked@AuditLog. ## Proving an annotation is invisible@SunsetusesRetentionPolicy.CLASSinstead: the compiler still writes it into the.classfile (so bytecode tools can see it), but the JVM never loads it into memory, soisAnnotationPresentreturnsfalsefor it at runtime — even though the annotation is sitting right there in the source.Ledger.javaproves this directly instead of leaving it as a claim in a comment. ## Wiring it all togetherEverything so far has been tested in isolation.
WarehouseApp.javais the last piece. Itsmainmethod that builds a small fleet, weighs it, restocks it, and audits it. That exercisesCrate,Fleet, andLedgerin the order a real warehouse report would: snapshot inventory, then restock, then audit. It prints the results so the whole pipeline is visible in one run. -
Challenge
Step 6: See where Java enforces your types
Now that you have completed all of the tasks, you can see where Java actually enforces the rules you wrote: in the running app, in the compiled bytecode, and in the compiler itself. Everything below runs in the Terminal tab. ### Run the warehouse report
bash runApp.shThis compiles the project and runs the
WarehouseApp.mainyou wrote in Task 5.3. With the reference solution you see:Total weight: 30 Audit trail: [adjustInventory, recordShipment] Sunset invisible: falseTotal weightis the sum of the crates you built withCrate.of(...)(the reference solution uses 10 and 20). It leaves out the zero-weight crates fromfillWithDefaults, because you weighed the fleet first. Both calls take the sameList<Crate<Integer>>: your producer-extendstotalWeightfrom Task 3.1 reads from it, and your consumer-superfillWithDefaultsfrom Task 3.2 writes to it.Audit trailis your Task 5.1 reflection finding the two@AuditLogmethods. The last line is whatverifySunsetInvisible()from Task 5.2 got back fromisAnnotationPresent(Sunset.class):false. Reflection can't see@Sunset, even though it sits right abovelegacyReconcile()inLedger.java. ### Find @Sunset in the compiled classThe annotation isn't gone. Look inside
Ledger.class:javap -v -cp target/classes lab.Ledger | grep -E "void |Annotations:|lab\.(AuditLog|Sunset)"public void recordShipment(java.lang.String); RuntimeVisibleAnnotations: lab.AuditLog public void adjustInventory(java.lang.String, int); RuntimeVisibleAnnotations: lab.AuditLog public void legacyReconcile(); RuntimeInvisibleAnnotations: lab.Sunsetjavapprints what the compiler wrote into the class file. CLASS retention kept@Sunsetthere, underRuntimeInvisibleAnnotations.@AuditLogis underRuntimeVisibleAnnotations, and only that kind is loaded when the JVM loads the class. That is whyauditTrail()finds two methods andverifySunsetInvisible()finds nothing. One value in@Retentiondecides which list an annotation lands in. ### Let the compiler check the boundStart
jshellwith your compiled classes on the class path:jshell --class-path target/classesThe first time it starts,
jshellmay printINFO: Created user preferences directory.You can ignore it.At the
jshell>prompt, enter these one line at a time. The last line is a deliberate mistake, so expect an error:import lab.* Crate.largerOf(Crate.of(3), Crate.of(9)).getContents() Crate.largerOf(Crate.of(3), Crate.of("nine"))The first call prints
==> 9. Yourof()from Task 2.2 inferredCrate<Integer>from each argument, and yourlargerOffrom Task 2.3 picked the bigger crate throughcompareContentsfrom Task 2.1. You never wrote a type argument. The second call fails on purpose. Instead of running it,jshellprints anError:block whosereason:isinference variable T has incompatible bounds, withequality constraints: T,java.lang.String,java.lang.Integer. The same inference refuses to choose aTthat is bothIntegerandString, so the mistake never reaches runtime.Type
/exitto leavejshell. Your crate toolkit now turns type mistakes into compiler errors instead of runtime crashes, and its audit metadata is visible exactly where you decided it should be.
About the author
Real skill practice before real-world application
Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.
Learn by doing
Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.
Follow your guide
All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.
Turn time into mastery
On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.