java:这是什么:[Ljava.lang.Object ;?

我得到这个,当我调用toString对象从一个函数调用接收。我知道对象的类型是编码在这个字符串,但我不知道如何读取它。这种类型的编码叫什么?
[Ljava.lang.Object;是Object []。类的名称,java.lang.Class表示Object的数组类。

命名方案记录在Class.getName()

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 (07002).

If this class object represents a primitive type or void, then the name returned is 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:

06000

这里有些例子:

// xxxxx varies
System.out.println(new int[0][0][7]); // [[[I@xxxxx
System.out.println(new String[4][2]); // [[Ljava.lang.String;@xxxxx
System.out.println(new boolean[256]); // [Z@xxxxx

数组上的toString()方法以这种格式返回String的原因是因为数组不会@Override从Object继承的方法,它指定如下:

The 07003 returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@’, and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

06002

注意:你不能依赖任何任意对象的toString()遵循上面的规范,因为他们可以(通常做)@覆盖它返回别的东西。检查任意对象类型的更可靠的方法是调用getClass()(一个最终方法继承自Object),然后在返回的Class对象上调用reflecting。理想情况下,API应该被设计为不需要反射(参见Effective Java 2nd Edition,Item 53:Prefer interfaces to reflection)。

在一个更有用的数组toString

java.util.Arrays为原始数组和Object []提供了toString重载。还有deepToString,你可能想要用于嵌套数组。

这里有些例子:

    int[] nums = { 1, 2, 3 };

    System.out.println(nums);
    // [I@xxxxx

    System.out.println(Arrays.toString(nums));
    // [1, 2, 3]

    int[][] table = {
            { 1, },
            { 2, 3, },
            { 4, 5, 6, },
    };

    System.out.println(Arrays.toString(table));
    // [[I@xxxxx, [I@yyyyy, [I@zzzzz]

    System.out.println(Arrays.deepToString(table));
    // [[1], [2, 3], [4, 5, 6]]

还有Arrays.equals和Arrays.deepEquals通过其元素以及许多其他与数组相关的实用程序方法来执行数组相等性比较。

相关问题

> Java Arrays.equals() returns false for two dimensional arrays. – 深入报道

http://stackoverflow.com/questions/3442090/java-what-is-this-ljava-lang-object

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:java:这是什么:[Ljava.lang.Object ;?