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.
A default constructor is only provided if you DON'T provide a constructor AT ALL. The wrapper classes are not provided with default constructors because they already have a constructor.
It is because all primitive wrapper classes (Integer, Byte, Long, Float, Double, Character, Boolean, and Short) are immutable in Java, so operations like addition and subtraction create a new object and not modify the old.
All the wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class Number. The object of the wrapper class contains or wraps its respective primitive data type. Converting primitive data types into object is called boxing, and this is taken care by the compiler.
Note: Structure fields that you declared as fillers are included in the program call; but the array wrapper classes do not include public get or set methods for those structure fields.
Java designers probably aren't too abstract in their decisions and couldn't find many similarities between numeric types (e.g. Integer
) and non-numeric types (e.g. Boolean
) to group them by a superclass.
Though, all the numeric types extend Number
which truly represents "numeric values that are convertible to the primitive types byte
, double
, float
, int
,long
, short
".
Actually, all the wrapper classes have a common interface Comparable<T>
(e.g. Comparable<Integer>
for Integer
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With