Question

I just came accross this behavior, as I wrote a dumpObject method using Reflection.

to reproduce:

public static class Tester {
        private String[] objects = new String[] { "a", "b", "c" };
    }

    public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
        System.out.println("testing Reflection");
        Tester tester = new Tester();
        Class<? extends Tester> class1 = tester.getClass();
        for (Field f : class1.getDeclaredFields()) {
            System.out.println(f);
            if (!f.isAccessible()) {
                f.setAccessible(true);
            }
            Object object = f.get(tester);
            System.out.println(object);
        }

    }

in this case, the object retrieved via f.get(tester) method is returning an array of String. If an Object can be actually an array, why is this illegal?

Object o = new String[]{"a", "b"};
Was it helpful?

Solution

From the Java Tutorials. Arrays:

An array is a container object that...

From Java Language Specification. Chapter 10. Arrays:

In the Java programming language, arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2). All methods of class Object may be invoked on an array.

In short, any array is an Object.

OTHER TIPS

Object o = new String[]{"a", "b"};

Is perfectly legal java code:

Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.

http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top