Returning a generic in java without casting it?

sf8193 :

I have an interface like so

public interface ClientBuilder <Client> {

    Client build();

}

and it's being used in a function like this

private static Service createImpl(ClientBuilder clientBuilder) {
        return new serviceImpl((x) clientBuilder.build());
    }

Is there a way where I wouldn't have to type cast it, so that I can remove the (x)? It's not entirely necessary, just would be a nice to have

Elliott Frisch :

Yes. You make ClientBuilder generic in the function. And, you should follow Java naming conventions. serviceImpl looks like a method name (and x looks like a variable not a class name). But using your names, something like

private static Service createImpl(ClientBuilder<x> clientBuilder) {
    return new serviceImpl(clientBuilder.build());
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=374568&siteId=1