tags:

views:

190

answers:

3

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?

+1  A: 

You should use:

myClass test = new myClass( Double.class, 15 );

You were missing the .class part.

Jason Cohen
His question is can you do it with out the .class (just pass Double)
hhafez
+1  A: 

You should also have

myClass(Class<T> type, int size)
Milhous
+4  A: 

You can't use Class names as input parameters in Java. The Object.class was introduced to allow the passing of "Class names"

So the answer is No, you can't pass Number as a parameter but you can pass Number.class. That is what it is for :)

** Update **

Also from you second constructor definition

myClass(Number n, int size)
{
    array = (T[]) Array.newInstance(n.getClass(), size);
}

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

hhafez