0

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

2 Answers2

0

One easy solution is to add a single parameter to your function Class<T>, where you'd call it like such:

generic(optionalOfInteger, Integer.class, 0), as an example

The other method you might be able to use involves utilizing reflection, and is documented here: Get type of a generic parameter in Java with reflection

However, keep in mind that reflection-based approaches can be quite slow.

Alex Hart
  • 1,663
  • 12
  • 15
0

Wouldn't be better to use

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

This way the user of your method will have to provide the class of the entity he wants to get?

Hasasn
  • 810
  • 8
  • 9