Home > database >  Java generic type-casting method to return Optional
Java generic type-casting method to return Optional

Time:03-31

Java 8 here. 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 can I make to load(...) to allow it to return an Optional of <T> T?

CodePudding user response:

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);
}
  • Related