简体   繁体   中英

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> ?

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

You can type-cast the given object inside the load() method either like that:

T result = (T) myObject;

or by making use of the of cast() method of the Class<T> class:

T result = objectClass.cast(myObject);

The only difference that in the first case, the compiler will issue a warning for unchecked type-cast.

In order to create an optional object from the nullable value, you have to use the static method Optional.ofNullable() which will create an empty optional if the given value is null . Conversely, method Optional.of() with throw a NullPointerException if you pass a null reference to it.

So the return clause of your method might be written like this:

return Optional.ofNullable(objectClass.cast(myObject));

or

return Optional.ofNullable((T) myObject);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM