Rafael T
Rafael T

Reputation: 15679

Why can Object be actually Object[]?

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"};

Upvotes: 0

Views: 60

Answers (2)

Matthew Wilson
Matthew Wilson

Reputation: 2065

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

Upvotes: 4

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

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.

Upvotes: 4

Related Questions