[英]Generic type for static method
Is there a way I can make the static method toObject
generic by passing the T class and return type T?有没有办法通过传递 T class 和返回类型 T 来使 static 方法
toObject
通用对象?
public class JsonUtil {
private JsonUtil() {
}
public static Object toObject(String jsonString, Class clazz, boolean unwrapRootValue) throws TechnicalException {
ObjectMapper mapper = new ObjectMapper();
mapper.writerWithDefaultPrettyPrinter();
if (unwrapRootValue) mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
try {
return mapper.readValue(jsonString, clazz);
} catch (IOException e) {
throw new TechnicalException("Exception while converting JSON to Object", e);
}
}
}
Sure.当然。 Just specify a generic type parameter on the method itself, and use it for both the return type and the
clazz
parameter:只需在方法本身上指定一个泛型类型参数,并将其用于返回类型和
clazz
参数:
public static <T> T toObject(String jsonString, Class<T> clazz,
boolean unwrapRootValue) throws TechnicalException {
/* ... */
}
public class JsonUtil {
private JsonUtil() {
}
public static <T> T toObject(String jsonString, Class<? extends T> clazz, boolean unwrapRootValue) throws TechnicalException {
ObjectMapper mapper = new ObjectMapper();
mapper.writerWithDefaultPrettyPrinter();
if (unwrapRootValue) mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
try {
return mapper.readValue(jsonString, clazz);
} catch (IOException e) {
throw new TechnicalException("Exception while converting JSON to Object", e);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.