简体   繁体   中英

Flexible return type of method

I have a couple of classes (extending AsyncTaskLoader) that all basically do the same thing: make a REST call and create POJOs from the response with Gson. Now I thought it would be more elegant to have just one class (let it take some parameters) and just tell it what kind of object I expect to get back. As a parameter I would give the class of the POJO that I expect to get back because it is used in the Gson deserialization like

Imprint impr = gson.fromJson(responseString, Imprint.class);

What would be the return type of the class / method? I thought about letting it return java.lang.Object and then downcast it to the POJO type object that I expect, but is there a better possibility?

Use generics. An example method signature could look like

public <T> T callService(String parameters, Class<T> clazz)

你可以使用uwe解决方案,或者只返回泛型类(这里是asynctask),然后做一个强制转换,甚至返回Object,然后做一个强制转换(更危险)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM