我刚刚遇到了这种行为,因为我使用反射编写了一个 dumpObject 方法。
重现:
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);
}
}
在这种情况下,通过f.get(tester)
方法检索的对象返回一个字符串数组。如果一个对象实际上可以是一个数组,为什么这是非法的?
Object o = new String[]{"a", "b"};
最佳答案
An array is a container object that...
来自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 classObject
may be invoked on an array.
简而言之,任何数组都是对象
。
关于java - 为什么Object实际上可以是Object[]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23499859/