← 中文资源

简体中文版本

ClassValue 惰性按类元数据缓存

用 java.lang.ClassValue 按 Class 惰性缓存反射元数据:并发安全且不阻碍类卸载,支持 remove 主动失效并触发重算。

阅读英文原文

实现说明

真正干活的是类 SchemaFieldCache、Invoice、Customer和函数 main、computeValue,其余都是接线。

使用要点

  • 外部依赖项保持为零,语言内置运行时已经全部满足。
  • 直接运行文件,输出会带上标签,比如 Invoice 1st:、Invoice 2nd:、Customer 1st:——输出的每一行都能指回产生它的那次调用。
  • 执行文件,main 会按顺序走完 computeValue。

常见问题

运行「ClassValue 惰性按类元数据缓存」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 Invoice 1st:、Invoice 2nd:、Customer 1st: 这类标签。

主要签名是 public static void main(String[] args)

核心语句

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

代码示例

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());
    }
}