泛型类型的内容需要显示

时间:2020-01-10 15:15:11

标签: java json parsing generics types

我有一些从json文件生成的实体类。我想检查我的实体类是否正确,所以我有一个parseDescriptor方法并正在读取值ttoa通用类类型。有人可以告诉我如何显示通用类对象的内容吗?

public <T> T parseDescriptor(String json, Class<T> c) throws IOException {
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.getDeserializationConfig().disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
            mapper.getDeserializationConfig().enable(DeserializationConfig.Feature.USE_ANNOTATIONS);
            T ret = mapper.readValue(json, c);
            if (!(ret instanceof ReportDescriptor)) {
                throw new IllegalArgumentException("The specified class of type "+c.getCanonicalName()+" does not extend ReportDescriptor");
            }
            return ret;
        }
        catch (JsonParseException jpe) {
:
:

1 个答案:

答案 0 :(得分:1)

如果ret是ReportDescriptor的实例,则可以将对象强制转换为该类。然后,您可以使用该类的功能来完成所需的操作。

//Cast the object
ReportDescriptor reportDescriptor = (ReportDescriptor) ret;
//For example, call the toString() function of that class
reportDescriptor.toString();
相关问题