Return generic Result<Foo<Bar>>

Viewed 114

I have a generic class, that contains a result of type T or an error message. It has two convenience methods for creation:

public class Result<T> {

    private String errorMessage;
    private T result;

    ...

    public static <S> Result<S> ok(S body) {
        return new ServiceResult<S>(body);
    }

    public static <S> Result<S> error(String errorMessage, Class<S> clazz) {
        return new ServiceResult<S>(errorMessage);
    }

}

With the given methods I am able to create type save results of most types. The problem that I am facing now is that I am not able to create an error service result of a type that is itself generic. Any help is very welcome!

To further specify the problem imagine I want to return results of type List<String>. If the result is successfully created I can create my result using the ok() method:

List<String> myStringList = ...;
Result<List<String>> result = Result.ok(myStringList);

If on the other hand an error occurred and I want to return an error result of the same type, then the provided method will not work, as it is not possible to create a Class<List<String>>:

// error, List<String>.class does not compile
Result<List<String>> result = Result.error("Error message", List<String>.class);
// error, result is of type Result<List>
Result<List<String>> result = Result.error("Error message", List.class);
2 Answers
public static <S> Result<S> error(String errorMessage, Class<S> clazz) {
    return new ServiceResult<S>(errorMessage);
}

This doesn't actually use clazz. So, remove the parameter, and you won't need to supply a value.

Result<List<String>> errorResult = error("whatever");

You can use ParameterizedTypeReference instead of class itself.

In this case, you will be able to use

Result.error("Error message", new ParameterizedTypeReference<List<String>>() {})

instead of

Result.error("Error message", List<String>.class);

Related