gpt4 book ai didi

java - 如何让 Java 中的方法接受类类型变量?

转载 作者:行者123 更新时间:2023-12-02 09:35:07 26 4
gpt4 key购买 nike

我有以下方法:

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) 进行调用。

如果我想创建一个从 StringClass 的映射,然后迭代该映射以将字符串反序列化为对象,我应该使用什么类型?

例如,我想要类似的东西:

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 - 如何让 Java 中的方法接受类类型变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57585955/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com