commons-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Frank W. Zammetti" <>
Subject Re: [BeanUtils] Handling array creation?
Date Thu, 08 Sep 2005 03:33:28 GMT
Niall Pemberton wrote:
> If they're always String[] then Thomas's solution is fine - but do you want
> to be able to handle other types? LazyDynaBean does something pretty similar
> to this - have a look at the growIndexedProperty() method for dynamically
> growing arrays and createIndexedProperty() method for instantiating new
> arrays.

Actually, I spent a while trying to crack this nut and then it occurred 
to me that since these objects are configured via XML, all I'm going to 
have basically *are* Strings anyway, so Thomas's solution will do the trick.

If and when I want to support other data types, I could do something like:

String type = (PropertyUtils.getPropertyType(obj, "myArray")).getName();
if (type.equalsIgnoreCase("string")) {
   String[] o = new String[values.size()];
   BeanUtils.setProperty(obj, "myArray", values.toArray(o));
} else if (type.equalsIgnoreCase("integer")) {
   Integer[] o = new Integer[values.size()];
   BeanUtils.setProperty(obj, "myArray", values.toArray(o));
// ... and so on for all supported types

I wouldn't claim that's pretty code, but it would get the job done.  I 
could only support those types that BeanUtils can automatically convert 
to anyway (ignoring the possibility of custom converters), so it's not 
all that bad an answer I think.

> Anyway the java.lang.reflect.Array has useful (static) methods for
> manipulating arrays...
> 1) Instantiating an Array
>      Object myArray = Array.newInstance(type.getComponentType(), arraySize);
> 2)  Setting a value in an array, e.g....
>      Array.set(myArray, index, value);
> 3) Finding the length of an array
>      Array.getLength(myArray);
> Niall

Yep, knew about these already... unfortunately, the one thing that would 
make this a piece of cake is not available here, or in Java t all: 
dynamic casting.  If you could do that, it would be trivial to do 
something like:

Class type = PropertyUtils.getPropertyType(obj, "myArray");
Object v = Array.newInstance(type, values.size());
BeanUtils.setProperty(obj, "myArray", values.toArray((type.getName())v));

That still assumes that getName() returned the type in a useable form, 
which of course it doesn't anyway (which complicates my above if block, 
but I digress), so my pipe dream is even more so :)

I think I'm good to go for now.  I can re-visit this at a later time. 
FYI, I took a look at the LazyDynaBean code... I'm not sure it would 
help from my initial reading of it, but I want to take another look and 
make sure I didn't miss something.  Thanks for pointing it out in any case!


To unsubscribe, e-mail:
For additional commands, e-mail:

View raw message