【问题标题】:Mapping int to Boolean将 int 映射到布尔值
【发布时间】:2013-01-02 12:35:12
【问题描述】:

Dozer(v. 5.3.2) 可以将 int 类型映射到 Boolean(Wrapper) 类型吗?

【问题讨论】:

    标签: java dozer


    【解决方案1】:

    通过粗略阅读文档,您可以通过自定义 BeanMapping 将几乎任何内容映射到任何内容,所以...“是”

    【讨论】:

    • 但是,是否可以按照与C语言相同的规则进行自动转换?
    • 是的——你必须写一些简单的东西,比如return i != 0
    【解决方案2】:

    是的....您可以将 int 类型映射到 Boolean 或任何其他数据类型。对于这种映射,您需要Custom Converters

    【讨论】:

      【解决方案3】:
          public class NewDozerConverter 
          extends DozerConverter<Integer, Boolean> {
      
        public NewDozerConverter() {
          super(Integer.class, Boolean.class);
        }
      
        public Boolean convertTo(Integer source, Boolean destination) {
          if (source > 1) {
            return Boolean.TRUE;
          } else if (source < 0) {
            return Boolean.FALSE;
          }
          throw new IllegalStateException("Unknown value!");
        }
      
        public Integer convertFrom(Boolean source, Integer destination) {
          if (Boolean.TRUE.equals(source)) {
            return 1;
          } else if (Boolean.FALSE.equals(source)) {
            return 0;
          }
          throw new IllegalStateException("Unknown value!");
        }
      
      } 
      

      【讨论】:

      • convertTo(Integer source, Boolean destination) 应该考虑源整数等于 1 或 0 的情况。更新代码:` public Boolean convertTo(Integer source, Boolean destination) { if (source >= 1) { return Boolean 。真的; } else if (source
      • 这段代码充满了错误。 :) 首先,'source' 在两个函数中都可能为 null。其次,convertTo(...) 对 convertFrom(...) 返回的两个值中的任何一个都抛出异常!也就是说,convertTo(convertFrom(Boolean.TRUE, null)) 抛出 IllegalStateException。在任何一种方法中,您都不需要也不需要“目的地”。这是无用的,因为无论如何方法都无法更改该值。最后,convertTo(Integer val) 应该只是 { return null != val && val != 0 }。
      【解决方案4】:

      如果您只需要将 0 和 1 分别映射为 false 和 true,则 Dozer 开箱即用即可处理。如果要将 0 映射为 false 并将任何其他值映射为 true,则需要 custom converter

      【讨论】:

        猜你喜欢
        • 2019-06-09
        • 2019-07-03
        • 2014-11-27
        • 1970-01-01
        • 2021-04-08
        • 2011-04-30
        • 2021-01-16
        • 2019-01-12
        • 2016-07-20
        相关资源
        最近更新 更多