On 9/7/05, Frank W. Zammetti <[EMAIL PROTECTED]> wrote:
> I can certainly explain why the above isn't valid... myArray is private
> in myBean, so I can't do the above because I simply don't have access to
> that field. If it was public then the above would work fine and I
> wouldn't have a question :)
That much is clear :-)
> The use case here is specifically for the DependencyFilter I add in Java
> Web Parts... basically, I'm instantiating a class based on a config
> file, and then configuring it (rudimentary IoC)... It already handles
> simple properties, Lists and Maps no problem, but arrays seemingly are a
> little trickier (and maybe I'm wrong about that to begin with) because
> of one thing I want to do: I don't want to force the class to have to
> create the array itself. I want to be able to have a list of values in
> the config file and create the array based on the number of elements,
> which of course could vary. So, I won't know the array size until the
> object is created.
So I take it that you either got a setter for this field, or you want
to use reflection directly (Field object).
But why shouldn't that work ? I mean, in the end arrays are normal
objects and can be used as such.
Eg. you can do something like:
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.beanutils.BeanUtils;
public class Main
{
public static class MyBean
{
private String[] myArray;
public String[] getMyArray()
{
return myArray;
}
public void setMyArray(String[] value)
{
myArray = value;
}
}
public static void main(String[] args) throws Exception
{
MyBean obj = new MyBean();
List values = new ArrayList();
values.add("String 1");
values.add("String 2");
// it is important to give the toArray method a base array to
define its return type
BeanUtils.setProperty(obj, "myArray", values.toArray(new String[0]));
System.out.println(obj.getMyArray());
}
}
Likewise, with Reflection you can do:
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public class Main
{
public static class MyBean
{
private String[] myArray;
public String[] getMyArray()
{
return myArray;
}
public void setMyArray(String[] value)
{
myArray = value;
}
}
public static void main(String[] args) throws Exception
{
MyBean obj = new MyBean();
List values = new ArrayList();
values.add("String 1");
values.add("String 2");
Field field = obj.getClass().getDeclaredField("myArray");
field.setAccessible(true);
field.set(obj, values.toArray(new String[0]));
System.out.println(obj.getMyArray());
}
}
Does that answer your question, or did I misunderstood you ?
regards,
Tom
---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]