java - 从泛型类型参数中检索高级信息
问题描述
我想知道 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();
}
解决方案
使用起来不会更好
public <T> T generic(final Optional<Class<T>> entityClazz, final Long id) throws EntityNotFoundException {
....
......
}
这样,您的方法的用户必须提供他想要获得的实体的类?
推荐阅读
- linux - 如何使用时间戳显示历史记录
- bro - BRO-IDS 如何将字符串与 NUL 终止符进行比较
- php - 如何使用 CodeIgniter 中的模板解析器将带有键的数组传递到视图中
- php - Maddhatter 日历视图未显示
- tightvnc - 如何在 Web 浏览器中使用 TightVNC
- javascript - 圆形进度条显示错误信息
- livecharts - 如何在实时图表中的图表上有一条斜线
- java - 在服务器端访问由超级账本作曲家休息服务器生成的安全休息 api
- javascript - 在 Tinymce 图像对话框中添加了图像大小建议文本
- java - Oracle 表单在 Java 1.6 上挂起并与 Java 1.8 一起使用