I was wondering if there is a possibility in Java 12 (minimum Java 8 required) to call T.class
on a generic type parameter, or if there is some workaround?
Since I'm against rewriting the same code logic over and over, I was currious about calling T.class
to pass any type of Java Object to my method and to write some mapping functionality to handle Optional<T>
unwrappging logic.
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();
}
I wish, that it would be possible to rewrite the above code like this:
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();
}