So I've run into something odd and I don't know what it's called so I'm having trouble finding out information about it, hence my question here.
I've run into an issue where if you create an array of any type and call getClass on this array in Java you will get an odd return. I am wondering why you get this specific return and what it means.
Code example is as follows:
byte[] me = new byte[1];
int[] me2 = new int[1];
double[] me3 = new double[1];
float[] me4 = new float[1];
String[] me5 = new String[1];
Integer[] me6 = new Integer[1];
System.out.println(me.getClass());
System.out.println(me2.getClass());
System.out.println(me3.getClass());
System.out.println(me4.getClass());
System.out.println(me5.getClass());
System.out.println(me6.getClass());
and the output is:
class [B
class [I
class [D
class [F
class [Ljava.lang.String;
class [Ljava.lang.Integer;
Those are the names of the underlying type object. The
[
indicates it's an array, and the following letter indicates the array type. B=byte, I=integer, D=double, etc. "L" is for class type members as you can see.It's just some stupid naming convention. Would been much better if they are more humanly readable:
class byte[]
,class java.lang.Integert[][]
Arrays don't have classes, they are simply data structures. The only thing having a class would be something extended from Object which is included in the array.
The toString method of Class invokes the getName method of Class which
The
[
at the start of the class name should be read as "array of ...", with "..." being what follows the[
; the conventions for what follows are spelled out in the documentation forClass.getName()
that @emory cited and linked to.Section 4.3.1 of the Java Language Specification starts: "An object is a class instance or an array." This suggests that arrays are not class instances. (Perhaps this is what @TigerTrussell was getting at in his answer.) However, Section 10.8 starts: "Every array has an associated Class object, shared with all other arrays with the same component type. The direct superclass of an array type is Object." This suggests that arrays are, if not true class instances, pretty darn close.
Unfortunately, the syntax rules for Java prohibit inheriting from an array type:
Note that this is a syntax constraint; there are no conceptual or semantic barriers (and it's allowed in many other OO languages).