KlasS # isAssignableFrom and unboxing / boxing

As you know, it Class#isAssignabledoes not take into account that the value can be automatically inserted into the box / unpacked. For example. the bottom of the four following cases returns 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 an already existing version of this method that will consider this case? (i.e. return truein all four of the above cases.) If not, what is the best way to implement this for all primitive / wrapped combinations?

+4
source share
2 answers

I have a WRAPPER_MAP field like this.

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

then I watch it.

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

Then test

wrap(clazz1).isAssignableFrom(wrap(clazz2));
+1
source

All Articles