Adams Bros Blog

8Dec/102

Java Array Reflection

In this article we talk about reflection with arrays in Java. Java array reflection is not difficult, but it can be trying to figure it out without a good example. Ultimately, what I needed was a way of injecting information into an array field. Of course, you need to inject the same "type" of array as the field is. That is what can be difficult to figure out, if you've never done it before.

In this example, I am using Java 1.6. I won't bother determining what is, or is not supported in prior versions of the Java language.


I may at some point create a "working" example, rather than a code snippet. But, if you've done reflection before, you should get the gist of what I'm doing here.

Basically, all we do is

  1. create a java.util.List object
  2. create a new array of the same type as the field we're reflecting
  3. ask the List object to insert all it's elements into the new array
  4. assign the array to the field.
            final Class<?> refType = field.getType();
            if (refType.isArray())
            {   // handle multiple ldap values
                final NamingEnumeration<?> values = attribute.getAll();

                final List<Object> ldapEntities = new ArrayList<Object>();
                while (values.hasMore())
                {   // iterate through all ldap attributes
                    final Object valueObject = values.next();
                    ldapEntities.add(getReferencedDN(agg.aggregateClass(),
                        dnReference, valueObject));
                }
                // convert to the array type used in the field
                // create an array the same size as the ldapEntities List
                final Object refArray = Array.newInstance(
                    refType.getComponentType(), ldapEntities.size());
                // ask List implementation to copy all elements to the new array
                final Object aggregatedList = ldapEntities.toArray(
                    (Object[]) refArray);
                field.setAccessible(true);
                field.set(object, aggregatedList);
                field.setAccessible(false);
            }
Comments (2) Trackbacks (0)
  1. won’t work for an array of a primitive type

  2. I thought it had worked when I tried it. Either that, or I changed it my code to work with native types, and didn’t update the blog. I’ll see if I can make sure the latest version is here.


Leave a comment

 

No trackbacks yet.