【问题标题】:How can I make a method accept a class type variable in Java?如何使方法接受 Java 中的类类型变量?
【发布时间】:2019-08-21 06:50:54
【问题描述】:

我有以下方法:

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

【问题讨论】:

    标签: java generics polymorphism


    【解决方案1】:

    你的语法非常接近!

    您应该使用Class&lt;?&gt;&lt;?&gt; 被称为通用通配符。

    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&lt;?&gt; 类型,因为deserialise 返回T,而不是Class&lt;T&gt;

    【讨论】:

    • 最后一个问题:我已经更新了问题中的代码,如何将Object obj 转换为其初始Class&lt;?&gt;(如Bar/Foo)以将其用作典型的Bar bar对象?
    • @JamesLarkin 你不知道obj 的实际类型,是吗?可能是FooBarobj 的类型会根据 for 循环所在的迭代而变化。
    • 确定这是有道理的。假设没有循环,请查看问题中更新的代码 #2。
    • 基本上我想做类似于stackoverflow.com/questions/57581859/… 的东西,但接受的答案并不适合我。
    • @JamesLarkin 你应该可以做到Bar bar = (Bar)objectMapper.readValue(json, typeClass);
    猜你喜欢
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    • 2018-10-24
    • 2020-09-14
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多