最佳实践:Java静态非最终变量 [英] Best Practice: Java static non final variables

查看:108
本文介绍了最佳实践:Java静态非最终变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,何时应使用静态非最终变量?

In Java, when should static non final variables be used?

例如

private static int MY_VAR = 0;

显然我们不是在谈论常数。

Obviously we are not talking about constants here.

public static final int MY_CONSTANT = 1;

根据我的经验,我经常在使用单身时证明他们是合理的,但后来我最终需要不止一个例子,让我非常头疼并重新考虑因素。

In my experience I have often justified them when using a singleton, but then I end up needing to have more than one instance and cause myself great headache and re-factoring.

似乎很少有它们应该在实践中使用。你怎么看?

It seems it is rare that they should be used in practice. What do you think?

推荐答案

统计收集可能会使用非最终变量,例如:计算创建的实例数。另一方面,对于那种情况,你可能想要使用 AtomicLong 等等,此时它可能是最终的。或者,如果您收集多个统计信息,最终可能会得到 Statistics 类以及对其实例的最终引用。

Statistics-gathering might use non-final variables, e.g. to count the number of instances created. On the other hand, for that sort of situation you probably want to use AtomicLong etc anyway, at which point it can be final. Alternatively if you're collecting more than one stat, you could end up with a Statistics class and a final reference to an instance of it.

拥有(合理地)非最终静态变量肯定是非常罕见的。

It's certainly pretty rare to have (justifiably) non-final static variables.

这篇关于最佳实践:Java静态非最终变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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