java - 比较两个类并考虑原始类及其包装类,看看它们是否相等

标签 java reflection equals equality

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

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;
}

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

最佳答案

最简单的方法是保留一个 primitive->boxed 类型的 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图书馆做到了。

关于java - 比较两个类并考虑原始类及其包装类,看看它们是否相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21227179/

相关文章:

java - 使用当前年份的 JPA/Hibernate 主键值序列

java - 对象的等于方法

list - 关于如何在序言中对列表中的元素求和的一些麻烦

java - 将 HashMap 的 ArrayList 转换为 GSON JsonArray

java - 返回 null 的构建器模式

java - 我应该如何解决这种错误

java - 当我们只有 .class 文件时如何转换对象?

c# - 为什么 GetProperties 两次列出 protected 属性(在通用基类中声明)?

c# - 替换 Net Core 中的 AppDomain

java - 为什么这个打印只有 "false"而不是 "false false"?