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
694k94 gold badges1.3k silver badges1.3k bronze badges
asked Oct 17, 2016 at 19:25
1

1 Answer 1

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;
 }
answered Oct 17, 2016 at 19:47

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.