简体   繁体   English

Class#isAssignableFrom和unboxing / boxing

[英]Class#isAssignableFrom and unboxing/boxing

As we know, Class#isAssignable does not consider, that a value can be auto boxed/unboxed. 我们知道, Class#isAssignable不会考虑,一个值可以自动装箱/取消装箱。 Eg the lower of the four following cases return false : 例如,以下四个案例中的较低者返回false

// obvious
System.out.println(boolean.class.isAssignableFrom(boolean.class)); // true
System.out.println(Boolean.class.isAssignableFrom(Boolean.class)); // true


// boxing/unboxing
System.out.println(boolean.class.isAssignableFrom(Boolean.class)); // false
System.out.println(Boolean.class.isAssignableFrom(boolean.class)); // false

Is there a pre-existing variant of this method which would consider this case? 是否存在此方法的预先存在的变体,会考虑这种情况? (ie returning true in all four given cases above.) If not, what would be the best way of implementing this for all primitive/wrapped combinations? (即在上面给出的所有四种情况下返回true 。)如果不是,那么对所有原始/包装组合实现这个的最佳方法是什么?

这个方法是关于子类型的,而不是一个值是否可以分配给变量,这要复杂得多,请参阅http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html# JLS-5.2

I have a WRAPPER_MAP field like this. 我有一个像这样的WRAPPER_MAP字段。

WRAPPER_MAP.put(boolean.class, Boolean.class);
// add others

then I look this up. 那我看看了。

public static Class wrap(Class clazz) {
     Class clazz2 = WRAPPER_MAP.get(clazz);
     return clazz2 == null ? clazz : clazz2;
}

Then the test is 那么测试就是

wrap(clazz1).isAssignableFrom(wrap(clazz2));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM