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

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


在日常开发中,我们常常需要将不同类型的对象转换为数值类型,比如 IntegerLong。为了简化这一过程,本文将介绍一个Java实现的对象转换器 ObjectConverter,它可以将各种类型的对象转换为 IntegerLong

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. 类简介

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

2. 构造方法

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

private ObjectConverter() {
}

3. 转换逻辑

3.1 整数转换(Integer)

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

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

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

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

支持的转换逻辑包括:

  • 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

5. 总结

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

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值