Skip to content
Advertisement

Generic type-casting method returning an Optional object

I have a method:

public LoadService {
    public <T> T load(String blobId, Class<T> objectClass) {
        // do stuff here
    }
}

That allows me to invoke it like so:

Fizz fizz = loadService.load("12345", Fizz.class);
Buzz buzz = loadService.load("23456", Buzz.class);

And this is great. Except, now, I want load(...) to return an Optional<???> so that the interaction would look something like:

Optional<Fizz> maybeFizz = loadService.load("12345", Fizz.class);
if (maybeFizz.isPresent()) {
   // etc.
}

Optional<Buzz> maybeBuzz = loadService.load("23456", Buzz.class);
if (maybeBuzz.isPresent()) {
   // etc.
}

What changes I need to make to load(...) method to make it capable of returning an Optional of <T>?

Advertisement

Answer

You can do it by declaring something like this.

public static <T> Optional<T> load(Object something, Class<T> clazz){
  return Optional.of((T)something);
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement