ClassValue Lazy Per-Class Metadata Cache

Cache per-Class reflection metadata lazily with java.lang.ClassValue, avoiding ClassLoader leaks while supporting explicit invalidation via remove.

JavaConfig Management

Code

snippet
import java.lang.reflect.RecordComponent;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class SchemaFieldCache {

    record Invoice(String id, long cents) {}
    record Customer(String name, String region, boolean active) {}

    public static void main(String[] args) {
        AtomicInteger inspections = new AtomicInteger();

        // ClassValue binds metadata weakly to each Class without pinning ClassLoaders
        ClassValue<List<String>> fieldNames = new ClassValue<>() {
            @Override
            protected List<String> computeValue(Class<?> type) {
                inspections.incrementAndGet();
                RecordComponent[] components = type.getRecordComponents();
                if (components == null) {
                    return List.of();
                }
                return Arrays.stream(components)
                        .map(RecordComponent::getName)
                        .toList();
            }
        };

        System.out.println("Invoice 1st:  " + fieldNames.get(Invoice.class) + " runs=" + inspections.get());
        System.out.println("Invoice 2nd:  " + fieldNames.get(Invoice.class) + " runs=" + inspections.get());
        System.out.println("Customer 1st: " + fieldNames.get(Customer.class) + " runs=" + inspections.get());

        // remove() invalidates only that Class entry so the next get() recomputes once
        fieldNames.remove(Invoice.class);
        System.out.println("Invoice post-remove: " + fieldNames.get(Invoice.class) + " runs=" + inspections.get());
    }
}

Step-by-step analysis — ClassValue Lazy Per-Class Metadata Cache

The working surface is the classes SchemaFieldCache, Invoice and Customer and the functions main and computeValue — everything else is wiring.

Watch out for

  • Dependencies remain zero because stock runtime primitives supply everything required.

Applying it

Core entry contract reads as public static void main(String[] args)

Output lines are prefixed (Invoice 1st:, Invoice 2nd:, Customer 1st:), exposing exact transition results directly inside sequential stdout lines.

Execute the file and main walks through computeValue, in that order.

Statements that matter

return List.of();
return Arrays.stream(components)
        .map(RecordComponent::getName)
        .toList();

Interactive Tools for This Topic

FAQ

What does ClassValue Lazy Per-Class Metadata Cache print when run?
The script runs standalone; its 4 labeled outputs include `Invoice 1st:`, `Invoice 2nd:`, `Customer 1st:`.