Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to convert/cast an Object to an array?

807603Jan 11 2008 — edited Jan 11 2008
I have been trying to re-use a method that accepts an Object parameter and handling the different types within it. Everything works as expected until I get to arrays. I have had very limited success in getting any useful information out of them. Ultimately, I would like to be able to use the following methods:
Arrays.asList()
Arrays.deepEquals()
Arrays.deepToString()
I can determine if the object is an array by using this:
obj.getClass().isArray();
I have tried to cast the object as a Object[], but I get a ClassCastException unless the actual type is an Object[]. I can determine several things about the array with this code:
obj.getClass().getCanonicalName();  // returns the array type; ie: boolean[], int[], java.lang.String[], etc.
obj.getClass().getComponentType();  // returns the actual array type; ie: boolean, int, java.lang.String, etc.
Array.getLength(obj);  // returns the number of items in the array
The Array.getLength() happily accepts an Object as the parameter. However, the Arrays methods I want to use only accept array-based parameters. I have tried accessing them by forcing a cast, like this:
Arrays.deepToString(obj.getClass().cast(obj));
But I get this error message in Eclipse: The method deepToString(Object[]) in the type Arrays is not applicable for the arguments (capture#19-of ? extends Object)*

I have also tried looking in the Array class to see how things are handled, but they are all native functions. I tried looking at the code in the Arrays class and came across something I thought might be able to help, but I really have no idea how to use it. The cloneSubarray() method seems to be working with arrays in an untyped manner, but retains a reference of the actual type.
private static <T> T[] cloneSubarray(T[] a)
{
  int n = to - from;
  T[] result = (T[])Array.newInstance(a.getClass().getComponentType(), n);
  System.arraycopy(a, from, result, 0, n);
  return result;
}
Having never used this designation before, I am not certain I fully understand it, but I believe it accepts any array type, creates a new one of the same type, populating it with the items from the original, and returns it. What I don't understand is the *<T>* after "static". I am not even sure if this could help me, but it looked promising.

So, my ultimate question, is it possible to take an Object and convert/cast it so that it works with the Arrays methods, without the need to check instanceof for each possible type?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 8 2008
Added on Jan 11 2008
1 comment
1,750 views