各种类型转换

这篇文章介绍了如何使用Java的ConverterUtil工具类实现Boolean类型的值转换为int类型,并展示了MapStruct中@Mapping注解用于字符串到long的转换实例。
摘要由CSDN通过智能技术生成

boolean转int类型

工具类

import java.lang.reflect.Field;

public class ConverterUtil {


    public static <T, U> void convertBooleanToInt(T source, U target) {
        Class<?> sourceClass = source.getClass();
        Class<?> targetClass = target.getClass();

        Field[] sourceFields = sourceClass.getDeclaredFields();

        for (Field field : sourceFields) {
            if (field.getType() == boolean.class || field.getType() == Boolean.class) {
                String fieldName = field.getName();
                String getterName = "is" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);

                try {
                    Field targetField = targetClass.getDeclaredField(fieldName);
                    Class<?> targetFieldType = targetField.getType();

                    if (targetFieldType == int.class || targetFieldType == Integer.class) {
                        boolean isAccessible = field.isAccessible();
                        field.setAccessible(true);
                        boolean fieldValue = (boolean) field.get(source);
                        field.setAccessible(isAccessible);

                        int intValue = fieldValue ? 1 : 0;

                        boolean isTargetAccessible = targetField.isAccessible();
                        targetField.setAccessible(true);
                        targetField.set(target, intValue);
                        targetField.setAccessible(isTargetAccessible);
                    }
                } catch (NoSuchFieldException | IllegalAccessException e) {

                }
            }
        }
    }

}

string 转long

@mapping mapstruct

    @Named("stringToLong")
    default long stringToLong(String value) {
        return Long.parseLong(value);
    }
@Mapping(source = "format.id",target = "id",qualifiedByName = "stringToLong")

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值