1

I have a method to build the array for the required type. It works for the primitive types. But when I have array of custom objects it doesn't work. So I have tweaked it. But still it fails. Code is like this :

    private Object buildArray(  String type,   Object object) {
    final Class<?> requiredType =  loadClass(type);
    final String typeName = type.substring(2).replace(";", "").trim();
        Object[] array = ((Object[]) object);
        ArrayList<Object> arrayList = new ArrayList<Object>(array.length);
        for (Object customObj : array) {
            arrayList.add(castToRequiredType(typeName, customObj));
        }
        return arrayList.toArray();
 }

In this castToRequiredType : casts the CustomObject to the CustomType where CustomType is a class. And array to be build is of type CustomType. I am stuck at dynamically building the array of CustomType.

Any help in this direction is welcome. Thanks in advance.

2
  • 1
    The intention of this code is really hard to understand. What is your overall goal with this? Commented Jun 23, 2011 at 11:38
  • overall goal is to invoke the API which takes a parameter of type customObject[]. And each CustomObject I have to build using castToRequiredType. This CustomObject can be MyCustoType, YourCustomType etc. Commented Jun 23, 2011 at 11:47

2 Answers 2

2

If you have an array of Object, you can use Arrays.copyOf to convert it to a different type:

CustomType[] ca = Arrays
  .copyOf(array, array.length, CustomType[].class);

Sign up to request clarification or add additional context in comments.

6 Comments

Well i tried replacing the last like like this return Arrays.copyOf(arrayList.toArray(), arrayList.size(), customType.newInstance()); but it doesn't compile The method copyOf(U[], int, Class<? extends T[]>) in the type Arrays is not applicable for the arguments (Object[], int, capture#40-of ?) Thanks for help :)
@java_enthu: There was a mistake in my answer, but I fixed it. This line replace your for-loop. You do not need to construct an ArrayList first. This works directly with your array.
@space_cowboy : I replace loop by Class<?> customType = loadClass(typeName); Arrays.copyOf(array, array.length,customType);Still i am getting the same compilation error. he method copyOf(U[], int, Class<? extends T[]>) in the type Arrays is not applicable for the arguments (Object[], int, Class<capture#40-of ?>)
@java_enthu: Sorry, It seems that indeed this approach does not work if class is not known at compile time.
Anyway thanks for quick help :) Any other approach or work around do you see which will be feasible?
|
1

Thanks I have solved it using Axis's Array Util For the same

Comments

Your Answer

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.