Categories
Java

Using reflection with arrays and primitive types

Sometimes it is necessary to handle a parameter of type object different for the real type. So you have to use instanceof to determine the type of an object. If you are need to check if it is an array, you can use the Reflection-API provided by the JRE. The Reflection API is a comfortable and rich functional API to inspect and manipulate Objects at runtime. One example could be to access private fields at runtime.

I had the problem to serialize some variables to JavaScript, so I wrote me a simple function:

1
public void objectToJavaScript(Object object, StringBuffer buf);

If the given object is primitive I would simple add it to the provided StringBuffer, but if it is an array I need to output ‘[‘ and ‘]’ with the given parameters. So I have to check if the object is an array:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void objectToJavaScript(Object object, StringBuffer buf) {
    if (object == null) {
        buf.append("null");
        return;
    }
    ... //other types
    if (object.getClass().isArray()) {
        buf.append('[');
        //TODO output array content
        buf.append(']');
        return;
    }
    ...
}

But how to access each entry of the array? One way could be to cast the object to Object[]. Unfortunately if the array is an array of primtive types this would throw a ClassCastException. So we have to use the functions, provided by java.lang.reflect.Array. The full code looks like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public void objectToJavaScript(Object object, StringBuffer buf) {
    if (object == null) {
        buf.append("null");
        return;
    }
    ... //other types
    if (object.getClass().isArray()) {
        buf.append('[');
        int len = java.lang.reflect.Array.getLength(object);
        for(int i = 0; i < len; i++) {
            if (i > 0) buf.append(',');
            objectToJavaScript(java.lang.reflect.Array.get(object, i), buf);
        }
        buf.append(']');
        return;
    }
    ...
}