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
- create a java.util.List object
- create a new array of the same type as the field we’re reflecting
- ask the List object to insert all it’s elements into the new array
- 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); } |