Java对象转换器:实现多类型转换为Integer和Long


文章目录
  • Java对象转换器:实现多类型转换为Integer和Long
  • 0. 完整代码
  • 1. 类简介
  • 2. 构造方法
  • 3. 转换逻辑
  • 3.1 整数转换(Integer)
  • 3.2 长整数转换(Long)
  • 4. 使用示例
  • 5. 总结



在日常开发中,我们常常需要将不同类型的对象转换为数值类型,比如

Integer

Long。为了简化这一过程,本文将介绍一个Java实现的对象转换器

ObjectConverter,它可以将各种类型的对象转换为

Integer

Long

0. 完整代码

package com.zibo.common.converter;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;

/**
 * 对象转换器
 * -
 * 提供将各种类型对象转换为 Integer 和 Long 类型的方法
 *
 * @author zibo
 * @date 2024/8/25 10:50
 * @slogan 慢慢学,不要停。
 */
public class ObjectConverter {

    // 私有构造函数,防止实例化
    private ObjectConverter() {
    }

    // 使用 Map 存储不同类型的 Integer 转换逻辑
    private static final Map<Class<?>, Function<Object, Optional<Integer>>> integerConverters = new HashMap<>();
    // 使用 Map 存储不同类型的 Long 转换逻辑
    private static final Map<Class<?>, Function<Object, Optional<Long>>> longConverters = new HashMap<>();

    static {
        // String 转换为 Integer 的逻辑
        integerConverters.put(String.class, source -> {
            try {
                return Optional.of(Integer.parseInt((String) source));
            } catch (NumberFormatException e) {
                // 当字符串无法解析为整数时,返回 Optional.empty()
                return Optional.empty();
            }
        });

        // BigInteger 转换为 Integer 的逻辑
        integerConverters.put(BigInteger.class, source -> {
            BigInteger bigInteger = (BigInteger) source;
            if (bigInteger.bitLength() <= 31) {
                // 检查 BigInteger 是否在 Integer 范围内
                return Optional.of(bigInteger.intValue());
            } else {
                // 超出范围则返回 Optional.empty()
                return Optional.empty();
            }
        });

        // BigDecimal 转换为 Integer 的逻辑
        integerConverters.put(BigDecimal.class, source -> {
            BigDecimal bigDecimal = (BigDecimal) source;
            if (bigDecimal.compareTo(BigDecimal.valueOf(Integer.MAX_VALUE)) <= 0 &&
                bigDecimal.compareTo(BigDecimal.valueOf(Integer.MIN_VALUE)) >= 0) {
                // 检查 BigDecimal 是否在 Integer 范围内
                return Optional.of(bigDecimal.intValue());
            } else {
                // 超出范围则返回 Optional.empty()
                return Optional.empty();
            }
        });

        // Long 转换为 Integer 的逻辑
        integerConverters.put(Long.class, source -> {
            Long longValue = (Long) source;
            if (longValue <= Integer.MAX_VALUE && longValue >= Integer.MIN_VALUE) {
                // 检查 Long 是否在 Integer 范围内
                return Optional.of(longValue.intValue());
            } else {
                // 超出范围则返回 Optional.empty()
                return Optional.empty();
            }
        });

        // Integer 类型不需要转换,直接返回
        integerConverters.put(Integer.class, source -> Optional.of((Integer) source));

        // 通用 Number 类型转换为 Integer 的逻辑
        integerConverters.put(Number.class, source -> Optional.of(((Number) source).intValue()));

        // String 转换为 Long 的逻辑
        longConverters.put(String.class, source -> {
            try {
                return Optional.of(Long.parseLong((String) source));
            } catch (NumberFormatException e) {
                // 当字符串无法解析为长整数时,返回 Optional.empty()
                return Optional.empty();
            }
        });

        // BigInteger 转换为 Long 的逻辑
        longConverters.put(BigInteger.class, source -> {
            BigInteger bigInteger = (BigInteger) source;
            if (bigInteger.bitLength() <= 63) {
                // 检查 BigInteger 是否在 Long 范围内
                return Optional.of(bigInteger.longValue());
            } else {
                // 超出范围则返回 Optional.empty()
                return Optional.empty();
            }
        });

        // BigDecimal 转换为 Long 的逻辑
        longConverters.put(BigDecimal.class, source -> {
            BigDecimal bigDecimal = (BigDecimal) source;
            if (bigDecimal.compareTo(BigDecimal.valueOf(Long.MAX_VALUE)) <= 0 &&
                bigDecimal.compareTo(BigDecimal.valueOf(Long.MIN_VALUE)) >= 0) {
                // 检查 BigDecimal 是否在 Long 范围内
                return Optional.of(bigDecimal.longValue());
            } else {
                // 超出范围则返回 Optional.empty()
                return Optional.empty();
            }
        });

        // Long 类型不需要转换,直接返回
        longConverters.put(Long.class, source -> Optional.of((Long) source));

        // Integer 转换为 Long 的逻辑
        longConverters.put(Integer.class, source -> Optional.of(((Integer) source).longValue()));

        // 通用 Number 类型转换为 Long 的逻辑
        longConverters.put(Number.class, source -> Optional.of(((Number) source).longValue()));
    }

    /**
     * 将对象转换为 Integer 类型
     *
     * @param source 源对象
     * @return 转换后的 Integer 类型的 Optional 包装
     */
    public static Optional<Integer> toInteger(Object source) {
        if (source == null) {
            // 如果源对象为 null,返回 Optional.empty()
            return Optional.empty();
        }

        // 从 Map 中获取对应类型的转换函数
        Function<Object, Optional<Integer>> converter = integerConverters.get(source.getClass());
        if (converter != null) {
            // 如果找到转换函数,执行转换
            return converter.apply(source);
        }

        // 如果没有对应的转换逻辑,返回 Optional.empty()
        return Optional.empty();
    }

    /**
     * 将对象转换为 Long 类型
     *
     * @param source 源对象
     * @return 转换后的 Long 类型的 Optional 包装
     */
    public static Optional<Long> toLong(Object source) {
        if (source == null) {
            // 如果源对象为 null,返回 Optional.empty()
            return Optional.empty();
        }

        // 从 Map 中获取对应类型的转换函数
        Function<Object, Optional<Long>> converter = longConverters.get(source.getClass());
        if (converter != null) {
            // 如果找到转换函数,执行转换
            return converter.apply(source);
        }

        // 如果没有对应的转换逻辑,返回 Optional.empty()
        return Optional.empty();
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 129.
  • 130.
  • 131.
  • 132.
  • 133.
  • 134.
  • 135.
  • 136.
  • 137.
  • 138.
  • 139.
  • 140.
  • 141.
  • 142.
  • 143.
  • 144.
  • 145.
  • 146.
  • 147.
  • 148.
  • 149.
  • 150.
  • 151.
  • 152.
  • 153.
  • 154.
  • 155.
  • 156.
  • 157.
  • 158.
  • 159.
  • 160.
  • 161.
  • 162.
  • 163.
  • 164.
  • 165.
  • 166.
  • 167.
  • 168.
  • 169.
  • 170.
  • 171.
  • 172.
  • 173.
  • 174.

1. 类简介

ObjectConverter类是一个工具类,旨在通过使用MapFunction接口来提供灵活的对象转换机制。它的主要功能是将不同类型的对象转换为IntegerLong,并使用Optional包装结果,以处理转换失败的情况。

2. 构造方法

该类的构造方法是私有的,意味着无法实例化。这种设计模式通常用于工具类中,仅包含静态方法:

private ObjectConverter() {
}
  • 1.
  • 2.

3. 转换逻辑

3.1 整数转换(Integer)

对于Integer转换,ObjectConverter使用了一个静态的Map来存储不同类型到Integer的转换逻辑:

private static final Map<Class<?>, Function<Object, Optional<Integer>>> integerConverters = new HashMap<>();
  • 1.

以下是一些支持的转换逻辑:

  • String → Integer:尝试解析字符串为整数,如果解析失败则返回Optional.empty()
  • BigInteger → Integer:检查BigInteger是否在Integer范围内,如果是则转换,否则返回Optional.empty()
  • BigDecimal → Integer:类似于BigInteger的处理逻辑。
  • Long → Integer:检查Long值是否在Integer范围内。
  • Integer:无需转换,直接返回。
  • Number → Integer:通过NumberintValue()方法获取整数值。
3.2 长整数转换(Long)

对于Long转换,逻辑与Integer类似:

private static final Map<Class<?>, Function<Object, Optional<Long>>> longConverters = new HashMap<>();
  • 1.

支持的转换逻辑包括:

  • String → Long:解析字符串为长整数。
  • BigInteger → Long:检查范围后转换。
  • BigDecimal → Long:检查范围后转换。
  • Long:直接返回。
  • Integer → Long:通过longValue()方法转换。
  • Number → Long:通过NumberlongValue()方法获取长整数值。

4. 使用示例

以下是如何使用ObjectConverter进行对象转换的示例:

Optional<Integer> intValue = ObjectConverter.toInteger("123");
Optional<Long> longValue = ObjectConverter.toLong(BigInteger.valueOf(12345L));

intValue.ifPresent(System.out::println);  // 输出: 123
longValue.ifPresent(System.out::println); // 输出: 12345
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

5. 总结

ObjectConverter类通过使用MapFunction接口,提供了一种灵活且可扩展的方式来处理对象到数值类型的转换。通过返回Optional,有效地处理了转换失败的情况,避免了NullPointerException