What is this: [Ljava.lang.Object;?

I get this when I call toString on an object I received from a function call. I know the type of the object is encoded in this string, but I don't know how to read it.

What is this type of encoding called?

135470 次浏览

[Ljava.lang.Object; is the name for Object[].class, the java.lang.Class representing the class of array of Object.

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

如果这个类对象表示一个不是数组类型的引用类型,则返回类的二进制名称,如 Java 语言规范(13.1)所指定的。

如果此类对象表示基元类型或 void,则返回的名称是与基元类型或 void对应的 Java 语言关键字。

如果此类对象表示一类数组,则名称的内部形式由元素类型的名称组成,该名称前面有一个或多个表示数组嵌套深度的 '['字符。 The encoding of element type names is as follows:

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

你的是最后一个,下面是一些例子:

// 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的原因是,数组不返回从 Object继承的方法 @Override,具体如下:

类 ABC1的 toString方法返回一个字符串,该字符串由对象是其实例的类的名称、 at-sign 字符‘@’和对象的哈希代码的无符号十六进制表示形式组成。换句话说,此方法返回的字符串等于:

getClass().getName() + '@' + Integer.toHexString(hashCode())

注意 : 您不能依赖任何任意对象的 toString()来遵循上述规范,因为它们可以(通常也确实如此) @Override返回其他内容。检查任意对象类型的更可靠的方法是在其上调用 getClass()(从 Object继承的 final方法) ,然后在返回的 Class对象上调用 反思。不过,在理想情况下,应该将 API 设计成不需要反射(参见 有效的 Java2nd 版,项目53: 更喜欢接口而不是反射)。


关于更“有用”的数组 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.equalsArrays.deepEquals,它们通过元素执行数组相等性比较,以及许多其他与数组相关的实用工具方法。

Related questions

如果你来这里是因为 Liquibase 的错误:

Caused By: Precondition Error
...
Can't detect type of array [Ljava.lang.Short

而你却在吸毒

not {
indexExists()
}

先决条件多次,那么你就面临着一个老问题: Https://liquibase.jira.com/browse/core-1342

我们可以尝试使用裸 sqlCheck(Postgres)执行以上检查:

SELECT COUNT(i.relname)
FROM
pg_class t,
pg_class i,
pg_index ix
WHERE
t.oid = ix.indrelid
and i.oid = ix.indexrelid
and t.relkind = 'r'
and t.relname = 'tableName'
and i.relname = 'indexName';

其中 tableName-是一个索引表名称和 indexName-是一个索引名称