Featured resource
2026 Tech Forecast
2026 Tech Forecast

1,500+ tech insiders, business leaders, and Pluralsight Authors share their predictions on what’s shifting fastest and how to stay ahead.

Download the forecast
  • Lab
    • Libraries: If you want this lab, consider one of these libraries.
    • Core Tech
Labs

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 platform
Lab Info
Level
Intermediate
Last updated
Nov 24, 2026
Duration
55m

Contact sales

By clicking submit, you agree to our Privacy Policy and Terms of Use, and consent to receive marketing emails from Pluralsight.
Table of Contents
  1. 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 — the main entry 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 steps

    Each remaining step targets one classic Java type-safety trap:

    1. 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.
    2. Step 3 — Fleet's wildcard methods currently either won't compile or hand back a useless Object; you'll apply PECS (producer-extends, consumer-super) and fix a wildcard-capture problem.
    3. Step 4 — Loader's varargs method can throw ClassCastException at runtime because of type erasure, and Storage shows the same class of failure happening through arrays instead of generics.
    4. Step 5 — AuditLog and Sunset look identical in source but behave completely differently at runtime because of one annotation attribute: retention policy.

    By the time WarehouseApp.main runs at the end, every one of these will be fixed and wired together.

  2. Challenge

    Step 2: Build the bounded generic Crate foundation

    Bounded type parameters

    Crate<T> needs to compare the crates it holds, but a bare T only supports equals and hashCode, and nothing that expresses "bigger" or "smaller". A bounded type parameter, T extends Comparable<T>, tells the compiler that whatever T turns out to be, it will have a compareTo method it can call directly, with no casts. That bound is already declared on the Crate<T> class in Crate.java; your job is to put it to use. ## Inference through a factory method

    With compareContents working, the next friction point is construction. Writing new Crate<Integer>(5) everywhere is noisy, and Crate.<Integer>of(5) is worse. A static generic method with its own type parameter lets the compiler infer T from the argument you pass in, so Crate.of(5) alone is enough. This is the same inference mechanism behind List.of(...) and friends in the standard library. ## Reusing the bound in a second static method

    Because the class-level bound guarantees compareTo exists, any generic method operating on Crate<T> values can lean on compareContents instead of re-deriving a comparison from scratch. largerOf is the first place that pays off: it takes two crates and returns whichever one wins the comparison, entirely through methods you've already written.

  3. Challenge

    Step 3: Make wildcard fleet operations usable

    PECS: producer-extends

    Fleet needs to total up weights from a list of crates, but callers might hand it a List<Crate<Integer>>, or a List<SpecialCrate> if SpecialCrate extends Crate<Integer>. A wildcard List<? 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-super

    The 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 of Crate<Integer> or anything broader, like List<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 capture

    Sometimes a caller only has List<? extends Crate<?>>, which is an unknown crate type inside an unknown crate type, and still needs a real, usable Crate<?> back, not just Object. 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 concrete T internally, and hand back something callers can actually use.

  4. Challenge

    Step 4: Expose and fix erasure and covariance traps

    Type erasure and heap pollution

    At runtime, List<T> becomes plain List, 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 @SafeVarargs promises the compiler on your behalf. ## Arrays are covariant, generics are not

    String[] is a subtype of Object[], which means arrays are covariant: you can store a String[] in an Object[] variable and the compiler is happy. But the array still remembers its real element type at runtime, so storing the wrong type through that Object[] reference throws ArrayStoreException. Generic lists made the opposite trade-off: List<String> is not a subtype of List<Object>, so the equivalent mistake is a compile error instead of a runtime crash. Storage.java puts both side by side.

  5. Challenge

    Step 5: Wire in annotation-driven auditing and finish the app

    Retention policy is a design decision

    AuditLog.java and Sunset.java each declare an annotation, but with different @Retention values. @AuditLog uses RetentionPolicy.RUNTIME, so the JVM keeps it in memory and reflection can see it on a loaded class. Ledger.java uses that to build an audit trail: scanning a class's declared methods and picking out the ones marked @AuditLog. ## Proving an annotation is invisible

    @Sunset uses RetentionPolicy.CLASS instead: the compiler still writes it into the .class file (so bytecode tools can see it), but the JVM never loads it into memory, so isAnnotationPresent returns false for it at runtime — even though the annotation is sitting right there in the source. Ledger.java proves this directly instead of leaving it as a claim in a comment. ## Wiring it all together

    Everything so far has been tested in isolation. WarehouseApp.java is the last piece. Its main method that builds a small fleet, weighs it, restocks it, and audits it. That exercises Crate, Fleet, and Ledger in 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.

  6. 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.sh
    

    This compiles the project and runs the WarehouseApp.main you wrote in Task 5.3. With the reference solution you see:

    Total weight: 30
    Audit trail: [adjustInventory, recordShipment]
    Sunset invisible: false
    

    Total weight is the sum of the crates you built with Crate.of(...) (the reference solution uses 10 and 20). It leaves out the zero-weight crates from fillWithDefaults, because you weighed the fleet first. Both calls take the same List<Crate<Integer>>: your producer-extends totalWeight from Task 3.1 reads from it, and your consumer-super fillWithDefaults from Task 3.2 writes to it.

    Audit trail is your Task 5.1 reflection finding the two @AuditLog methods. The last line is what verifySunsetInvisible() from Task 5.2 got back from isAnnotationPresent(Sunset.class): false. Reflection can't see @Sunset, even though it sits right above legacyReconcile() in Ledger.java. ### Find @Sunset in the compiled class

    The 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.Sunset
    

    javap prints what the compiler wrote into the class file. CLASS retention kept @Sunset there, under RuntimeInvisibleAnnotations. @AuditLog is under RuntimeVisibleAnnotations, and only that kind is loaded when the JVM loads the class. That is why auditTrail() finds two methods and verifySunsetInvisible() finds nothing. One value in @Retention decides which list an annotation lands in. ### Let the compiler check the bound

    Start jshell with your compiled classes on the class path:

    jshell --class-path target/classes
    

    The first time it starts, jshell may print INFO: 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. Your of() from Task 2.2 inferred Crate<Integer> from each argument, and your largerOf from Task 2.3 picked the bigger crate through compareContents from Task 2.1. You never wrote a type argument. The second call fails on purpose. Instead of running it, jshell prints an Error: block whose reason: is inference variable T has incompatible bounds, with equality constraints: T,java.lang.String,java.lang.Integer. The same inference refuses to choose a T that is both Integer and String, so the mistake never reaches runtime.

    Type /exit to leave jshell. 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

Pluralsight’s AI authoring technology is designed to accelerate the creation of hands-on, technical learning experiences. Serving as a first-pass content generator, it produces structured lab drafts aligned to learning objectives defined by Pluralsight’s Curriculum team. Each lab is then enhanced by our Content team, who configure the environments, refine instructions, and conduct rigorous technical and quality reviews. The result is a collaboration between artificial intelligence and human expertise, where AI supports scale and efficiency, and Pluralsight experts ensure accuracy, relevance, and instructional quality, helping learners build practical skills with confidence.

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.

Get started with Pluralsight