gpt4 book ai didi

java - 如何查看在堆内存中创建的对象数?

转载 作者:搜寻专家 更新时间:2023-11-01 03:49:21 26 4
gpt4 key购买 nike

我想在运行我的程序时查看 Java 创建了多少对象。

我的意图是如果我使用代码 String s = new String("Hi");我想看看 Java 将创建多少对象。稍后我想尝试 String news = "Hi";

这是我的示例程序:

import java.util.Scanner;

public class Test {
public static void main(String[] args) {
String str = new String("Hi");
Scanner s = new Scanner(System.in);
s.nextLine();
}
}

我正在使用 Scanner只是为了避免程序终止。

我已经阅读了这篇 SO 帖子 How to find the number of objects in the heap并尝试使用 jvisualvm ,但该工具没有给出我在类(class)中创建的对象的数量。我也不明白如何根据下图获取对象的实际数量。

enter image description here

当我尝试使用命令 jmap -heap <pid> 时然后我得到以下错误:

Attaching to process ID 15101, please wait... Error attaching to process: sun.jvm.hotspot.debugger.DebuggerException: Can't attach to the process

如果我使用 eclipse Debug 作为选项,那么我发现这不是找出正在创建的对象数量的正确方法。

最佳答案

如果你查看你的调试器你可以看到

enter image description here

String@437 对象在 s1 s2 s3 中是相同的,但它指的是一个 char[2]@438 这是另一个对象。因此,您有两个对象。

关于java - 如何查看在堆内存中创建的对象数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32718730/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com