编程语言
首页 > 编程语言> > java-比较两个类,并考虑基本类型及其包装器类是否相等

java-比较两个类,并考虑基本类型及其包装器类是否相等

作者:互联网

最后,我想做一些类似的事情,我将用它来搜索正确的构造函数以进行反射.

public static boolean equalWithPrimitive(Class<?> from, Class<?> target){
    if(from == target){
        return true;
    }else if((from == Byte.class || from == byte.class) && (target == Byte.class || target == byte.class)){
        return true;
    }else if((from == Short.class || from == short.class) && (target == Short.class || target == short.class)){
        return true;
    }else if((from == Integer.class || from == int.class) && (target == Integer.class || target == int.class)){
        return true;
    }else if((from == Long.class || from == long.class) && (target == Long.class || target == long.class)){
        return true;
    }else if((from == Float.class || from == float.class) && (target == Float.class || target == float.class)){
        return true;
    }else if((from == Double.class || from == double.class) && (target == Double.class || target == double.class)){
        return true;
    }else if((from == Boolean.class || from == boolean.class) && (target == Boolean.class || target == boolean.class)){
        return true;
    }else if((from == Character.class || from == char.class) && (target == Character.class || target == char.class)){
        return true;
    }
    return false;
}

有没有更短而准确的方法来实现这一想法?

解决方法:

最简单的方法是在执行检查之前保留一个原始->盒装类型的Map并将其用于转换:

private static final Map<Class, Class> primitiveWrapperMap = new HashMap();
static {
     primitiveWrapperMap.put(Boolean.TYPE, Boolean.class);
     primitiveWrapperMap.put(Byte.TYPE, Byte.class);
     primitiveWrapperMap.put(Character.TYPE, Character.class);
     primitiveWrapperMap.put(Short.TYPE, Short.class);
     primitiveWrapperMap.put(Integer.TYPE, Integer.class);
     primitiveWrapperMap.put(Long.TYPE, Long.class);
     primitiveWrapperMap.put(Double.TYPE, Double.class);
     primitiveWrapperMap.put(Float.TYPE, Float.class);
     primitiveWrapperMap.put(Void.TYPE, Void.TYPE);
}

public static Class primitiveToWrapper(Class cls) {
    Class convertedClass = cls;
    if (cls != null && cls.isPrimitive()) {
        convertedClass = (Class) primitiveWrapperMap.get(cls);
    }
    return convertedClass;
}

public static boolean equalWithPrimitive(Class<?> from, Class<?> target) {
    return primitiveToWrapper(from) == primitiveToWrapper(to);
}

这也是apache commons ClassUtils库的工作方式.

标签:reflection,equals,equality,java
来源: https://codeday.me/bug/20191122/2058054.html