Pau Chorro Pau Chorro - 1 year ago 75
Java Question

Cast generic T to Object[]

Is it possible to cast a generic into a Object[] if not what is the way?

public class OneClass<T extends Serializable> {

public void someMethod()
T castObject = (T) value;
//The method createArrayOf(String, Object[]) in the type Connection is not applicable for the arguments (String, T)
//So method signature is createArrayOf(String, Object[])
Array array = connection.createArrayOf("integer", castObject);


But I would want to use this generic as next:




Answer Source

Sure, it is possible; say:

T whatever = ... coming from somewhere

Object[] castedObjects = (Object[]) whatever;

If its a good idea; that might be a whole lot different discussion. But in order to have that discussion, we would have to see more "context" - what are your requirements; what is the intention of that class; what is it supposed to do with those arrays of object?!

But your immediate problem can easily be fixed; as shown above.