Is there a particular reason behind java wrapper classes (java.lang.Integer
, java.lang.Boolean
, ...) not having a common supertype ?
I'm asking because it would be quite handy to have (e.g.) WrapperType::getType
function along the classic Object::getClass
which would return the class of the primitive type.
More specifically, the context is invoking constructors via reflection where you only have the Class<T>
and the parameters Object[]
E.g:
public static <T> T createInstance(Class<T> clz, Object... params) throws Exception
In order to get the constructor I can get the parameter types via:
Class<?>[] c = Arrays
.stream(params)
.map(Object::getClass)
.toArray(Class<?>[]::new);
return clz.getConstructor(c).newInstance(params);
but this will of course fail with constructors like String::new(char[], int, int);
If that supertype existed I could do:
.map( o -> o.getClass().isPrimitive() ? ((WrapperType) o).getType() : o.getClass() )
I guess there is a particular reason java
developers did not implement it.
AnyVal
.Number
is the super class for all wrapper classes expectString
,Character
, andBoolean
. There's really no shared functionality betweenNumbers
,String
,Character
, andBoolean
other thantoString()
so there's no point in making a naming type as a super for the wrappers ti share.getConstructor
like that doesn't work anyway, because some methods accept boxed types (e.g.compareTo
) and sometimes the arguments to a method are subtypes of the parameter types. (Also,o.getClass().isPrimitive()
will always be false.) To do this correctly, you need to do applicability testing by testing every constructor or just know the parameter types ahead of time.