首页 > 解决方案 > 从泛型类型参数中检索高级信息

问题描述

我想知道 Java 12(至少需要 Java 8)中是否有可能调用T.class泛型类型参数,或者是否有一些解决方法?

因为我反对一遍又一遍地重写相同的代码逻辑,所以我对调用T.class将任何类型的 Java 对象传递给我的方法并编写一些映射功能来Optional<T>处理解包逻辑感到好奇。

public SpecificEntity specific(final Long id) throws EntityNotFoundException {
    final Optional<SpecificEntity> optional = this.specificEntityRepository.findById(id);
    if (optional.isEmpty()) {
      throw new EntityNotFoundException(SpecificEntity.class, "id", id.toString());
    }
    return optional.get();
  }

我希望,可以像这样重写上面的代码:

public <T> T generic(final Optional<T> optional, final Long id) throws EntityNotFoundException {
    if (optional.isEmpty()) {
      throw new EntityNotFoundException(T.class, "id", id.toString());
    }
    return optional.get();
  }

标签: javagenerics

解决方案


使用起来不会更好

public <T> T generic(final Optional<Class<T>> entityClazz, final Long id) throws EntityNotFoundException {
     ....
     ......
  }

这样,您的方法的用户必须提供他想要获得的实体的类?


推荐阅读