Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't wrapper classes have a common supertype?

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.

like image 564
Marko Pacak Avatar asked Apr 26 '18 13:04

Marko Pacak


People also ask

Do wrapper classes have default constructors?

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.

Why are wrapper classes immutable?

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.

Which is the common parent class of numeric type wrapper classes?

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.

Do wrapper classes have set methods?

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.


1 Answers

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).

like image 54
Andrew Tobilko Avatar answered Oct 18 '22 19:10

Andrew Tobilko