GSON 是否应该声明为静态 final?
2022-09-04 19:19:17
						我在我的代码中使用Java Callable Future。以下是我的主要代码,它使用future和可调用性 -
以下是我的主要代码,它使用future和可调用性 -
public class TimeoutThread {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        Future<TestResponse> future = executor.submit(new Task());
        try {
            System.out.println(future.get(3, TimeUnit.SECONDS));
        } catch (TimeoutException e) {
        }
        executor.shutdownNow();
    }
}
下面是我的类,它实现了可调用接口,其中我使用 对我的服务器进行 REST URL 调用。然后,我将变量传递给我正在反序列化JSON字符串的方法,然后我正在检查密钥是否具有或在其中,然后基于该方法制作.TaskRestTemplateresponsecheckStringerrorwarningTestResponse
class Task implements Callable<TestResponse> {
    private static RestTemplate restTemplate = new RestTemplate();
    @Override
    public TestResponse call() throws Exception {
    String url = "some_url";            
    String response = restTemplate.getForObject(url, String.class);
    TestResponse response = checkString(response);
    }
}
private TestResponse checkString(final String response) throws Exception {
    Gson gson = new Gson(); // is this an expensive call here, making objects for each and every call?
    TestResponse testResponse = null;
    JsonObject jsonObject = gson.fromJson(response, JsonObject.class); // parse, need to check whether it is an expensive call or not.
    if (jsonObject.has("error") || jsonObject.has("warning")) {
        final String error = jsonObject.get("error") != null ? jsonObject.get("error").getAsString() : jsonObject
            .get("warning").getAsString();
        testResponse = new TestResponse(response, "NONE", "SUCCESS");
    } else {
        testResponse = new TestResponse(response, "NONE", "SUCCESS");
    }
    return testResponse;
}
所以我的问题是我应该如何在这里声明?是否应将其声明为 Task 类中的静态最终全局变量?因为目前我正在使用gson解析JSON,对于我所做的每个调用,哪一个是昂贵的还是不昂贵的?GSONnew Gson()
 
					 
				 
				    		 
				    		 
				    		 
				    		