Dynamic array creation
Hi all... here's a good one for you...
I have a situation where I have some bean, and I need to populate an
array field in it... here's the problem... I do not know the element
type of the array before runtime.
Now, I've been planning on using Commons Beanutils, since the rest of
this particular app does (it's doing a lot of introspection of the
beans and such).
So, here's the question... can anyone figure out a way to dynamically
create an array at runtime? What I mean is, I want to do the
followig:
PropertyUtils.setProperty(obj, fieldName,
((List)fieldValues).toArray());
So, I want to set the field named by fieldName on the bean instance
referenced by obj, and I want to do it by taking the fieldValues List
and converting it to an array. Now, I can do:
PropertyUtils.setProperty(obj, fieldName,
((List)fieldValues).toArray(new String[0]));
...and that's great, except that I don't know until runtime that the
field of the bean is of type String, it could be anything else. So,
how can I dynamically do the equivalent of the new String[0] is really
the question?
FYI, I don't really care if this is done with Beanutils, but I think
that's probably the logical course of action. Any ideas? Thanks all!
Oliver Wong - 02 Jun 2006 15:31 GMT
> Dynamic array creation
>
[quoted text clipped - 29 lines]
> FYI, I don't really care if this is done with Beanutils, but I think
> that's probably the logical course of action. Any ideas? Thanks all!
Use the Array.newInstance(Class, int) method:
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/Array.html#newInstance
(java.lang.Class,%20int)
(note that there's a close parenthesis at the end that's part of this URL).
- Oliver