Java类静态成员的作用域 [英] Scope of Java class static member

查看:166
本文介绍了Java类静态成员的作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java / JSP开发Web应用程序。
一个类,说Student,有一个静态成员
static private int _nextID;

I am developing a web application using Java/JSP. One class, say Student, has a static member static private int _nextID;

如果此 _nextID 在所有用户会话中是否相同?或者每个会话都有自己的_nextID?

I want to know, if this _nextID is the same among all user sessions? Or each session has its own _nextID?

推荐答案

在简单情况下 Student 的实例将共享同一个静态 nextID 字段。然而,人们应该考虑超越简单的情况(或文档,你没有)。在这种情况下,除非从 nextID 派生的实例 id 字段传播到更大的应用程序, ID应该是唯一的。在这种情况下,您需要一个更健壮的ID生成器(也许您需要一个 UUID ;也许你想要一个主键在数据库中;也许是别的东西)。

In the simple case, you can assume that multiple instances of Student will share the same static nextID field. However, one should think beyond the simple case (or document that you haven't). In this case, it's fine unless the instance id fields derived from the nextID counter propagate out into a larger application where the IDs are meant to be unique. In that case, you want a more robust ID generator (maybe you want a UUID; maybe you want a primary key in a database; maybe something else).

仔细询问自己需要的唯一ID范围是。然后寻找解决该问题并将其记录在类中的解决方案。

Ask yourself carefully what the required scope of the unique IDs is. Then seek a solution that solves that problem and document it in the class.

一般,同名类中的静态字段,由不同的类加载器(在相同或不同的JVM中)加载可能是不同的实例,最经常注意当尝试实现Singleton模式。因此,静态变量的范围取决于(在复杂的情况下)相关的类加载器。关于更多(最近)有关由classloader定义的Java命名空间的详细信息,请参阅和< a href =http://onjava.com/pub/a/onjava/2005/01/26/classloading.html =nofollow>此处。

In general, static fields within the same-named class, but loaded by different classloaders (in the same or in different JVMs) may be different instances, something people most often notice when trying to implement the Singleton pattern. So the scope of your static variable depends (in complicated cases) on the relevant classloaders. Some more (recent) detail about Java namespaces defined by classloader is here and here.

相关于SO: Thread.getContextClassLoader() ...

Related on SO: Difference between Thread.getContextClassLoader()....

这篇关于Java类静态成员的作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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