There is no contradiction.
An array is also an Object, albeit a special kind of Object.
It is like saying: An bird is also an animal, albeit a special kind of animal.
You can convince yourself by compiling and running the following Java code.
String[] arrayOfStrings = { "bla", "blah" };
// examine the class hierarchy of the array
System.out.println("arrayOfStrings is of type "
+ arrayOfStrings.getClass().getSimpleName()
+ " which extends from "
+ arrayOfStrings.getClass().getSuperclass().getSimpleName());
// assingning the array to a variable of type Object
Object object = arrayOfStrings;
The output will be
arrayOfStrings is of type String[] which extends from Object
Answer from Thomas Fritsch on Stack OverflowThere is no contradiction.
An array is also an Object, albeit a special kind of Object.
It is like saying: An bird is also an animal, albeit a special kind of animal.
You can convince yourself by compiling and running the following Java code.
String[] arrayOfStrings = { "bla", "blah" };
// examine the class hierarchy of the array
System.out.println("arrayOfStrings is of type "
+ arrayOfStrings.getClass().getSimpleName()
+ " which extends from "
+ arrayOfStrings.getClass().getSuperclass().getSimpleName());
// assingning the array to a variable of type Object
Object object = arrayOfStrings;
The output will be
arrayOfStrings is of type String[] which extends from Object
Arrays are special classes provided to you by Java itself. All of them inherit from common superclass Object. As they inherit from Object they of course can be used anywhere where Object is expected. Instances of arrays are indeed instances of those classes. One can even reference array classes as they do with other classes' literals:
Class<int[]> intArrayClass = int[].class;
I see no conflict.
This can be useful https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html#jls-10.8
Since Java 12
Class provides a method arrayType(), which returns the array type class whose component type is described by the given Class. Please be aware that the individual JDK may still create an instance of that Class³.
Class<?> stringArrayClass = FooBar.arrayType()
Before Java 12
If you don't want to create an instance, you could create the canonical name of the array manually and get the class by name:
// Replace `String` by your object type.
Class<?> stringArrayClass = Class.forName(
"[L" + String.class.getCanonicalName() + ";"
);
But Jakob Jenkov argues in his blog that your solution is the better one, because it doesn't need fiddling with strings.
Class<?> stringArrayClass = Array.newInstance(String.class, 0).getClass();
³ Thanks for the hint to Johannes Kuhn.
Since Java 12, there is the arrayType() method on java.lang.Class:
Class<?> arrayOfFooClass = fooClass.arrayType();
Its implementation just calls Array.newInstance(this, 0).getClass().