杰克逊从类创建JavaType [英] Jackson create JavaType from Class

查看:296
本文介绍了杰克逊从类创建JavaType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

必须有一种方法可以从String.class创建JavaType吗?

There must be a way to create a JavaType from String.class?

注意:在我的用例中,方法的输入必须 JavaType,因为该值是使用TypeFactory动态创建的.

Note: The input for the method must be JavaType for my use case because that value is created dynamically using TypeFactory.

/** Returns a JavaType for Map<String, valueType> **/
private static JavaType stringToJavaType(JavaType valueType) {
    TypeFactory typeFactory = objectMapper.getTypeFactory();
    // this does not compile, can't mix Class and JavaType
    return typeFactory.constructMapType(Map.class, String.class, valueType);
}

如果我想回答一个相关问题,相对于constructParametricTypeconstructMapType有什么优势?

If I may tack on a related question, what is the advantage of constructMapType over constructParametricType?

推荐答案

您可以通过以下方式实现:

You can do it by:

  • constructFromCanonical 方法.例如:typeFactory.constructFromCanonical(String.class.getName())
  • constructArrayType 方法.例如:typeFactory.constructArrayType(String.class).getContentType().但这看起来有点像变通办法.
  • SimpleType.constructUnsafe 方法.例如:SimpleType.constructUnsafe(String.class).文档中的注释:杰克逊核心类使用的方法:不能由应用程序代码使用:它不能正确处理超类型的检查,因此父类和已实现的接口都无法通过生成的类型实例进行访问.因此,甚至可以尝试使用它来避免这种情况.
  • constructFromCanonical method. For example: typeFactory.constructFromCanonical(String.class.getName())
  • constructType method. For example: typeFactory.constructType(new TypeReference<String>() {}).
  • constructArrayType method. For example: typeFactory.constructArrayType(String.class).getContentType(). But it looks a little bit like a workaround.
  • SimpleType.constructUnsafe method. For example: SimpleType.constructUnsafe(String.class). Note from documentation: Method used by core Jackson classes: NOT to be used by application code: it does NOT properly handle inspection of super-types, so neither parent Classes nor implemented Interfaces are accessible with resulting type instance. So, even it is possible to use try to avoid it.

这篇关于杰克逊从类创建JavaType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆