• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 364
  • Last Modified:

new array using reflection

Java generics don't allow me to do something like:

public static <T> void doStuff(T obj) {
    T[] arr = new T[5];
    // ...
}

It won't let me create the array of type T.

So, is it possible to create a new array of type T using reflection? Is there a method like to
    T.class.newInstance()
which will create an array of T?
0
HappyEngineer
Asked:
HappyEngineer
2 Solutions
 
marchentCommented:
u can use Object, which is parent of all java classes for generalize a data type

public static Object void doStuff(Object obj) {
    Object []arr = new Object[5];
    // ...
}

when u need to convert
String str = (String)obj; //convert into String
Integer i = (Integer)obj; //convert into Integer
but u have to make sure, that the object is actually belongs to String/Integer class

~marchent~
0
 
objectsCommented:
Object array = Array.newInstance(T.class, 10);
0
 
HappyEngineerAuthor Commented:
objects, that almost works, but T.class apparently isn't legal.

It says: "Illegal class literal for the type parameter T"
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
objectsCommented:
sorry, thought T was a class name, not a parameter.
0
 
objectsCommented:
what about:

Object array = Array.newInstance(obj.getClass(), 10);
0
 
Ajay-SinghCommented:
try this:


T[] arr = (T[]) new Object[5];
0
 
HappyEngineerAuthor Commented:
The casing of the array works at compile time but breaks at run time.

I can't call obj.getClass() because in this particular case I don't actually have an object to call getClass() on.

Never mind, I've worked around it. Thanks anyway!
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now