문제

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"};
도움이 되었습니까?

해결책

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.

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top