有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

具有数组类型的getClass方法Java

所以我遇到了一些奇怪的事情,我不知道它叫什么,所以我很难找到关于它的信息,所以我的问题在这里

我遇到了一个问题,如果您创建任何类型的数组并在Java中调用该数组上的getClass,您将得到一个奇怪的返回。我想知道你为什么会得到这个具体的回报,这意味着什么

代码示例如下所示:

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());

输出为:

 class [B
 class [I
 class [D
 class [F
 class [Ljava.lang.String;
 class [Ljava.lang.Integer;

共 (5) 个答案

  1. # 1 楼答案

    类名开头的[应该读作“数组…”,用“…”在[之后;@emory引用并链接到的Class.getName()文档中详细说明了以下内容的约定

    Section 4.3.1 of the Java Language Specification开始:“对象是类实例或数组。”这表明数组不是类实例。(也许这就是@TigerTrussell在回答中的意思。)但是,Section 10.8开始:“每个数组都有一个关联的类对象,与具有相同组件类型的所有其他数组共享。数组类型的直接超类是object。”这表明数组即使不是真正的类实例,也非常接近

    不幸的是,Java的语法规则禁止从数组类型继承:

    public class MyFancyArray extends int[] { // ILLEGAL
       // ...
    }
    

    请注意,这是一个语法约束;没有概念上或语义上的障碍(在许多其他OO语言中也是允许的)

  2. # 2 楼答案

    类的toString方法调用类的getName方法

    Returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String. If this class object represents a reference type that is not an array type then the binary name of the class is returned, as specified by The Java™ Language Specification.

    If this class object represents a primitive type or void, then the name returned is a String equal to the Java language keyword corresponding to the primitive type or void.

    If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more '[' characters representing the depth of the array nesting. The encoding of element type names is as follows:

     Element Type           Encoding
     boolean                Z
     byte                   B
     char                   C
     class or interface     Lclassname;
     double                 D
     float                  F
     int                    I
     long                   J
     short                  S 
    

    The class or interface name classname is the binary name of the class specified above.

    Examples:

     String.class.getName()
         returns "java.lang.String"
     byte.class.getName()
         returns "byte"
     (new Object[3]).getClass().getName()
         returns "[Ljava.lang.Object;"
     (new int[3][4][5][6][7][8][9]).getClass().getName()
         returns "[[[[[[[I"
    
  3. # 3 楼答案

    数组没有类,它们只是数据结构。唯一拥有类的东西是从数组中包含的对象扩展而来的东西

  4. # 4 楼答案

    这些是基础类型对象的名称。[表示它是一个数组,下面的字母表示数组类型。B=byte,I=integer,D=double,等等。正如您所看到的,L代表类类型的成员

  5. # 5 楼答案

    只是一些愚蠢的命名惯例。如果它们更人性化,那就更好了:class byte[]class java.lang.Integert[][]