0

I have a class which has the constructor

public Treque(Class<T> t) {

}

I need to instantiate an array which has the class t. How do I instantiate it?

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
wes
  • 1
  • 2
    https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Array.html#newInstance-java.lang.Class-int- – JB Nizet Oct 17 '16 at 19:30

1 Answers1

0

It depends on what your exact goal is. If you want something arbitrary, go with reflection. If you simply want to pass an object that inherits a class, you can do that with different syntax.

Since your example is using Class, try these reflection examples:

I think the accepted answer here is what you are looking for. Java Generics Creating Array from Class

And a little bit more:

    public void test(Class<T> t) {
            T[] a=new T[10];//complie error

        Object array = java.lang.reflect.Array.newInstance(t, 10);//lots of ambiguity
        String[] arrT = (String[]) array;//works if you know the final type

        Object[] anyType = new Object[10];
        for(int i=0;i<10;i++)
               anyType[i] = createObject(t.getName());
        //You will need to cast the Object to your desired type
        }
      static Object createObject(String className) {
          //http://www.java2s.com/Code/Java/Reflection/ObjectReflectioncreatenewinstance.htm
      Object object = null;
      try {
          Class classDefinition = Class.forName(className);
          object = classDefinition.newInstance();
      } catch (InstantiationException e) {
          System.out.println(e);
      } catch (IllegalAccessException e) {
          System.out.println(e);
      } catch (ClassNotFoundException e) {
          System.out.println(e);
      }
      return object;
   }
Community
  • 1
  • 1
ldmtwo
  • 419
  • 5
  • 14