1. Overview
1.概述
In this tutorial, we’ll learn what [Ljava.lang.Object means and how to access the proper values of the object.
在本教程中,我们将学习[Ljava.lang.Object的含义以及如何访问对象的正确值。
2. Java Object Class
2.Java对象类
In Java, if we want to print a value directly from an object, the first thing that we could try is to call its toString method:
在Java中,如果我们想直接从一个对象中打印一个值,我们可以尝试的第一件事是调用它的toString方法。
Object[] arrayOfObjects = { "John", 2, true };
assertTrue(arrayOfObjects.toString().startsWith("[Ljava.lang.Object;"));
If we run the test, it will be successful, but usually, it’s not a very useful result.
如果我们运行测试,将会成功,但通常,这不是一个非常有用的结果。
What we want to do is print the values inside the array. Instead, we have [Ljava.lang.Object. The name of the class, as implemented in Object.class:
我们要做的是打印数组内的值。相反,我们有[Ljava.lang.Object. 类的名称,如在Object.class中实现的。0px”>:
getClass().getName() + '@' + Integer.toHexString(hashCode())
When we get the class name directly from the object, we are getting the internal names from the JVM with their types, that’s why we have extra characters like [ and L, they represent the Array and the ClassName types, respectively.
当我们直接从对象中获取类名时,我们从JVM中获取的是带有类型的内部名称,这就是为什么我们有额外的字符如[和L,它们分别代表数组和ClassName类型。
3. Printing Meaningful Values
3.打印有意义的价值
To be able to print the result correctly, we can use some classes from the java.util package.
为了能够正确地打印结果,我们可以使用java.util包中的一些类。
3.1. Arrays
3.1.数组
For example, we can use two of the methods in the Arrays class to deal with the conversion.
例如,我们可以使用Arrays类中的两个方法来处理转换问题。
With one-dimensional arrays, we can use the toString method:
对于一维数组,我们可以使用toString方法。
Object[] arrayOfObjects = { "John", 2, true };
assertEquals(Arrays.toString(arrayOfObjects), "[John, 2, true]");
For deeper arrays, we have the deepToString method:
对于更深的数组,我们有deepToString方法。
Object[] innerArray = { "We", "Are", "Inside" };
Object[] arrayOfObjects = { "John", 2, innerArray };
assertEquals(Arrays.deepToString(arrayOfObjects), "[John, 2, [We, Are, Inside]]");
3.2. Streaming
3.2.流媒体
One of the significant new features in JDK 8 is the introduction of Java streams, which contains classes for processing sequences of elements:
JDK 8中的一个重要的新特性是引入了Java streams,它包含了用于处理元素序列的类。
Object[] arrayOfObjects = { "John", 2, true };
List<String> listOfString = Stream.of(arrayOfObjects)
.map(Object::toString)
.collect(Collectors.toList());
assertEquals(listOfString.toString(), "[John, 2, true]");
First, we’ve created a stream using the helper method of. We’ve converted all the objects inside the array to a string using map, then we’ve inserted it to a list using collect to print the values.
首先,我们使用辅助方法of创建了一个流。我们使用map将数组内的所有对象转换为字符串,然后我们使用collect将其插入到一个列表中以打印这些值。
4. Conclusion
4.总结
In this tutorial, we’ve seen how we can print meaningful information from an array and avoid the default [Ljava.lang.Object;.
在本教程中,我们看到了如何从一个数组中打印出有意义的信息,并避免使用默认的[Ljava.lang.Object;.。
We can always find the source code for this article over on GitHub.
我们可以随时在GitHub上找到这篇文章的源代码over。