Home > front end >  Generic type-casting method returning an Optional object
Generic type-casting method returning an Optional object

Time:03-31

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

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

CodePudding user response:

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