You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何获取Lambda返回类型及泛型<T>的Class对象?

如何在Java中获取泛型**的Class对象并结合FastJSON处理JSON?

核心代码片段

调用方代码

public Features findFeatureById(BigDecimal id) {
    return mixedCacheService.get(FEATURE, id.toString(), new MixedCacheService.Func<>(() -> featuresDao.selectById(id)));
}

被调用方代码

public <T> T get(@NotNull CacheBaseConstants cacheBaseConstants, @NotNull String key, @NotNull Supplier<T> getter) {
    String value = get(cacheBaseConstants, key);
    if ("".equals(value)) {
        return null;
    }
    // 如何在此处获取T.class?
    return Optional.ofNullable(value)
            .map(o -> JSON.parseObject(value, T.class))
            .orElseGet(() -> put(cacheBaseConstants, key, getter));
}

已尝试的方案

  • 继承com.alibaba.fastjson.TypeReference实现自定义Supplier包装类,但未成功捕获具体泛型类型:
public static class Func<T> extends TypeReference<T> {
    private Supplier<T> supplier;

    public Func(Supplier<T> supplier) {
        super();
        this.supplier = supplier;
    }

    public T get() {
        return supplier.get();
    }
}
  • 尝试通过getter.supplier.getClass().getGenericSuperclass()获取泛型父类,但返回结果为Object,无法提取有效泛型信息。

最终解决方案

通过继承Hutool的TypeReference实现抽象代理类,利用抽象类实例化时的泛型捕获特性,保留具体类型信息:

import cn.hutool.core.lang.TypeReference;
import java.util.function.Supplier;

public abstract class SupplierProxy<T> extends TypeReference<T> {
    private final Supplier<T> supplier;

    public SupplierProxy(Supplier<T> supplier) {
        super();
        this.supplier = supplier;
    }

    public T get() {
        return supplier.get();
    }
}

同时修改被调用方的get方法,通过SupplierProxy的getType()方法获取真实泛型类型,替换原本无法直接使用的T.class:

public <T> T get(@NotNull CacheBaseConstants cacheBaseConstants, @NotNull String key, @NotNull SupplierProxy<T> getter) {
    String value = get(cacheBaseConstants, key);
    if ("".equals(value)) {
        return null;
    }
    return Optional.ofNullable(value)
            .map(o -> JSON.parseObject(value, getter.getType()))
            .orElseGet(() -> put(cacheBaseConstants, key, getter));
}

单元测试验证

@Test
public void get() {
    Features actual = new Features();
    actual.setName("123");
    assertEquals(actual,mixedCacheService.get(FEATURE_BY_KEY, "1", new SupplierProxy<Features>(() -> actual) {
    }));
    assertEquals( actual,mixedCacheService.get(FEATURE_BY_KEY, "1", new SupplierProxy<Features>(() -> actual) {
    }));
}

内容的提问来源于stack exchange,提问作者finger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 04:22:03