I’m allocating an array of T, T extends Number inside a class. I can do it this way:
myClass test = new myClass(Double.class, 20);
Then the constructor itself:
myClass(Class<T> type, size) { array = (T[]) Array.newInstance(type, size); }
I’d like to know if it’s possible to do it like this:
myClass(Number n, size) { array = (T[]) Array.newInstance(n.getClass(), size); }
But, I’ve tried instatiating an object with the second constructor with:
myClass test = new myClass(Double, 15);
And it doesn’t work. Am I doing anything wrong, or is it just not possible?
You can’t use Class names as input parameters in Java. The
Object.classwas introduced to allow the passing of ‘Class names’So the answer is No, you can’t pass
Numberas a parameter but you can passNumber.class. That is what it is for 🙂** Update **
Also from you second constructor definition
It is clear the input parameter is an instance of Number or it’s subclasses not the class is itself. I know it is obvious but it makes clearer why it is not possible to do what you intended