java - 如何使方法接受 Java 中的类类型变量?
问题描述
我有以下方法:
public <T> T deserialise(String payload, Class<T> expectedClass) {
try {
return mapper.readValue(payload, expectedClass);
} catch (IOException e) {
throw new IllegalStateException("JSON is not valid!", e);
}
}
我可以使用deserialise("{\"foo\": \"123\"}", Foo.class)
.
如果我想创建一个映射 from String
toClass
然后遍历这个映射以将字符串反序列化为对象,我应该使用什么类型?
例如,我想要类似于:
Map<String, Class?> contents = ImmutableMap.of(
"{\"foo\": \"123\"}", Foo.class,
"{\"bar\": \"123\", \"bar2\": \"123\"}", Bar.class
);
然后我希望能够:
for (Map.Entry<String, Class?> e : contents.entrySet) {
Class? obj = deserialise(e.getKey(), e.getValue());
}
我应该放什么代替Class?
?
更新:
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Class<?>> contents = ImmutableMap.of(
"{\"foo\": \"123\"}", Foo.class,
"{ \"color\" : \"Black\", \"type\" : \"BMW\" }", Bar.class
);
for (Map.Entry<String, Class<?>> e : contents.entrySet()) {
try {
Object obj = objectMapper.readValue(e.getKey(), e.getValue());
System.out.println(obj);
} catch (IOException ex) {
ex.printStackTrace();
}
}
更新#2:
ObjectMapper objectMapper = new ObjectMapper();
String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
T typeClass = Foo.class; // TODO: fix syntax error
try {
Class<?> obj = objectMapper.readValue(json, typeClass); // TODO: fix error and cast obj to Foo.class using typeClass
} catch (IOException e) {
e.printStackTrace();
}
解决方案
您的语法非常接近!
你应该使用Class<?>
. 被<?>
称为通用通配符。
Map<String, Class<?>> contents = ImmutableMap.of(
"{\"foo\": \"123\"}", Foo.class,
"{\"bar\": \"123\", \"bar2\": \"123\"}", Bar.class
);
for (Map.Entry<String, Class<?>> e : contents.entrySet) {
Object obj = deserialise(e.getKey(), e.getValue());
}
请注意,obj
不应该是类型,Class<?>
因为deserialise
返回T
,而不是Class<T>
。
推荐阅读
- java - 我正在尝试使用回收器视图从 fire base 数据库中检索数据,但出现错误
- arrays - 系统verilog约束中的内部运算符中的数组切片
- clickhouse - Clickhouse 在“合并聚合数据”时很慢
- javascript - react-native 中的自定义警报控件
- asp.net-core - 将 .net core 2.1 升级到 .net core 2.2 时,Linq to excel 不起作用
- c# - 抽象类转换问题
- vue.js - 如何从数据库中获取 vue-i18n 的数据?
- python - 从间隔192分隔的列中获取最大值。使用python
- reactjs - export default Form.create()(...) -- 第二个括号到底是什么?
- android - 在 RTL 字符串中间使用 LTR 文本时 TextView 中的文本方向更改