且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java byte []到字符串转换输出字节

更新时间:2022-11-07 21:54:39

您所看到的

[B@1ef9f1d

是方法 toString()的结果,该方法的所有类都继承自 Object 类,因为Java中的所有类都扩展了 Object .这是实现为

is the result of the method toString() that all classes inherit from the Object class, since all classes in Java extend Object. This is implemented as

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

在这种情况下, getClass().getName()将返回 [B ",因为它是字节数组.

In this case, getClass().getName() would return [B because it is an array of Bytes.

这是因为Java中的数组对象没有自定义的 toString()方法,它们继承了 Object 的.

This is because array objects in Java do not have a custom toString() method, they inherit Object's.

如果要打印数组的内容,请尝试

If you want to print the contents of an array, try

Arrays.toString(yourByteArray);

对于自定义类,您应该始终实现(覆盖)自己的自定义 toString()方法.这对于日志记录很有用.请注意,将字符串串联与引用类型一起使用时,将隐式使用 toString()方法将您的对象转换为String表示形式.

For custom classes, you should always implement (override) your own custom toString() method. It is useful for logging. Note that String concatenation when used with reference types uses the toString() method implicitly to convert your object into a String representation.