首页 > 解决方案 > 如何使方法接受 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 StringtoClass然后遍历这个映射以将字符串反序列化为对象,我应该使用什么类型?

例如,我想要类似于:

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();
}

标签: javagenericspolymorphism

解决方案


您的语法非常接近!

你应该使用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>


推荐阅读