Dynamic Return Type in Java method

前端 未结 5 1937
隐瞒了意图╮
隐瞒了意图╮ 2021-02-02 14:20

I\'ve seen a question similar to this multiple times here, but there is one big difference.

In the other questions, the return type is to be determined by the parameter.

5条回答
  •  北荒
    北荒 (楼主)
    2021-02-02 14:57

    My 2 cents with an example with Google HTTP client:

    static public  Any getJson(final String url, final Class parseAs) throws IOException {
            HttpRequestFactory requestFactory
                    = HTTP_TRANSPORT.createRequestFactory(
                    (HttpRequest request) -> {
                        request.setParser(new JsonObjectParser(JSON_FACTORY));
                    });
    
            HttpRequest request = requestFactory.buildRequest(HttpMethods.GET, new GenericUrl(url), null);
    
            return request.execute().parseAs(parseAs);
        }
    

    Can be use like this:

    HashMap out = HttpUtils.getJson( "https://api.qwant.com", HashMap.class);
    

提交回复
热议问题