Tono Nam
Tono Nam

Reputation: 36058

How to call a method that requires a Class<T> object as a parameter?

I have a class where I need the constructor to initialize variable array. I researched on the internet and also stack overflow but now I am stuck on how to call the method. For example how could I call method1 in my example?

public class SomeClass<T>{

   public T[] array;

   //Constructor
   public SomeClass()
   {
        Method1(T, 5); //?  error
        Method1(5); //?   error
        Method1(new T().GetType(), 5); //? error
        // HOW CAN I CALL THAT METHOD?

        array = (T[])(new Object[5]); // this gives an error too
   }

   private void Method1(Class<T> type, int size)
   {
       array = (T[])Array.newInstance(type, size);
   }
}

Upvotes: 3

Views: 570

Answers (2)

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236004

Try this:

class SomeClass<T> {

    private T[] array;

    @SuppressWarnings("unchecked")
    public SomeClass(Class<T> klass, int size) {
        array = (T[]) Array.newInstance(klass, size);
    }

}

And to instantiate it:

SomeClass<Integer> example = new SomeClass<Integer>(Integer.class, 10);

Be aware that the array instantiated is an object array, and all its elements will be null until you explicitly assign them.

Upvotes: 5

Paul Bellora
Paul Bellora

Reputation: 55223

You would need to pass the Class object representing T into the SomeClass constructor:

public SomeClass(Class<T> clazz)
{
   array = Method1(clazz, 5);
}

This is necessary because of Type Erasure, which means T will have no meaning at runtime (Array.newInstance takes a Class object representing the array's element type for the same reason).

Upvotes: 3

Related Questions