Java打印String对象的地址

2年前 (2022) 程序员胖胖胖虎阿
199 0 0

一、System函数

当使用System.out.println()方法打印String类型对象时,会输出String对象代表的字符串,并不会输出对象的地址。因此,我们必须借助其他API来实现该功能。

java.lang.System类的方法

public static native int identityHashCode(Object x);
Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object’s class overrides hashCode(). The hash code for the null reference is zero.
Params: x – object for which the hashCode is to be calculated
Returns: the hashCode

无论给定对象的类是否覆盖hashCode(),返回给定对象的哈希码与默认hashCode()方法返回的哈希码相同。空引用的哈希码是零。默认hashCode()方法,即Object对象中的hashCode()方法

public native int hashCode();
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer)

在合理可行的情况下,由 Object 类定义的 hashCode() 方法为不同的对象返回不同的整数。 (通常将对象的内部地址转换为整数),也就是说Object类的hashcode()方法返回对象的地址。

二、实现代码

一般,被打印的对象的形式为:java.lang.Object@1ff9dc36,由全限定类名+@+十六进制数组成。

为了打印的字符串对象的形式和一般形式相同,我们还需要使用另外两个方法,

String.class.getName() 返回全限定类名java.lang.String;
Integer.toHexString(int) 将十进制数转换为十六进制数并返回;

代码如下及运行结果:
Java打印String对象的地址
参考代码:

public class StringObjectAddrTest {

    public static void main(String[] args) {

        String str = "HelloWorld";
        System.out.println(String.class.getName() + "@" + Integer.toHexString(System.identityHashCode(str)));

        // 与Object对比
        System.out.println(new Object());
    }

}

版权声明:程序员胖胖胖虎阿 发表于 2022年11月10日 上午5:56。
转载请注明:Java打印String对象的地址 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...