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?
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?
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;
}