al bundy
al bundy

Reputation:

Is there a way to pass a Number as a parameter in Java?

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?

Upvotes: 2

Views: 241

Answers (3)

hhafez
hhafez

Reputation: 39750

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

Upvotes: 4

Milhous
Milhous

Reputation: 14643

You should also have

myClass(Class<T> type, int size)

Upvotes: 1

Jason Cohen
Jason Cohen

Reputation: 83021

You should use:

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

You were missing the .class part.

Upvotes: 1

Related Questions