在Java中的哪里初始化静态字段? [英] Where to initialize static fields in java?

查看:64
本文介绍了在Java中的哪里初始化静态字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个类,其中一个需要计算创建对象的次数(称为lastId的int字段).在c ++中,我们必须在主类中初始化静态字段值,然后才能在其他类中正确使用该静态字段并计算已创建的对象数量.Java呢?我必须在哪里初始化静态字段值.另外,我知道如何计算对象是否已创建,但是如果对象已删除怎么办?Java中没有析构函数,那么如何完成这项工作?

I have a couple of classes, one of which needs to count how many times object has been created (int fields called lastId). In c++ we had to initialize static fields value in main class and then we were able to correctly use that static field in other classes and count how many objects have been created. What about java? Where do I have to initialize static fields value. Also, I know how to count if object has been created, but what about if object has been deleted? There are no destructors in java, so how can this job be done?

推荐答案

如果您只想计算类型调用的 active 对象的数量

If all you want to do is count the number of active objects of a type call

jps -lvm  # to find the pid of your process
jmap -histo {pid} # count all objects in the system

jmap -histo:live {pid} # count objects referenced

这将按类别为您提供实例数量的计数.

This will give you a count of the number of instances, by class.

如果您想形象地查看应用程序在做什么,请尝试

If you wnt to visualise what you application is doing try

jvisualvm

这将提供诸如已用内存,线程等的统计信息,以及有关此处正在消耗CPU和创建对象的统计信息.

This will give stats like memory used, threads etc as well a break down of here CPU is being consumed and which objects are created.

那java呢?

您只需使用类似的东西初始化它们

You just initialise them with something like

static int counter = 0;

我必须在哪里初始化静态字段值.

Where do I have to initialize static fields value.

与初始化其他任何字段相同的地方.

The same place you would initialise any other field.

顺便说一句,如果您只是这样做

BTW if you did just this

static int counter;

无论如何,默认情况下它将是0,所以我怀疑您不需要初始化它.

It would be 0 by default anyway, so I suspect you don't need to initialise it.

如果对象已删除该怎么办?

what about if object has been deleted?

这很容易,因为您不能删除对象.因此答案始终为0.;)

That's easy because you can't delete objects. So the answer is always 0. ;)

java中没有析构函数,那么如何完成这项工作?

There are no destructors in java, so how can this job be done?

Java没有这种东西,所以这个问题毫无意义.

Java doesn't have such a thing so the question is kind of meaningless.

这篇关于在Java中的哪里初始化静态字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆