静态字段的范围是什么? [英] what's the scope of a static field?

查看:167
本文介绍了静态字段的范围是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在静态字段遇到问题。我认为根本原因必须是静态字段的范围。

I meet a problem in static field. I think the root cause must be the scope of the static field.

该项目基于Apache servicemix,由许多子项目组成。

The project is based on Apache servicemix and consists of many sub-projects.

在子项目'A'中,我在注册类中定义了一个静态列表字段reg,并使用了一些静态方法来操作该字段,如'add'和'得到所有'。部署子项目A后,项目A的名称将被添加到静态列表中以进行注册。

In sub-project 'A', I defined a static list field 'reg' in class 'Registration' and some static method to operate the field like 'add' and 'getAll'. Once the sub-projectA is deployed, the name of the project 'A' will be added into the static list for registration.

问题在于项目'B',当部署子项目'B'时,我希望它的名称将被添加到完全相同的静态列表中进行注册。但是当我调用静态方法getAll或添加注册时,子项目B中的'reg'似乎与子项目A中的'reg'完全不同。所以注册功能不起作用。

The problem is when it comes to sub-project 'B', when the sub-project 'B' is deployed, I want its name would be added into the exactly same static list for registration. But when I call static method getAll or add on 'Registration', it seems that the 'reg' in sub-projectB is totally different from the one in sub-projectA. So the registration function doesn't work.

所以我想问一个基本问题,静态字段的范围是什么?它在JVM或其他一些东西中是否有效?

So I want to ask one basic question, what's the scope of a static field? Is it valid in a JVM or some other things?

感谢您的帮助

推荐答案

静态的范围是全局的 - 在它自己的类加载器中。 JVM可以创建多个类加载器,并在每个新的类加载器中加载类的单独实例。

The scope of a static is global - within its owning classloader. A JVM can create multiple classloaders and load separate instances of your class in each of new classloaders.

每个JVM的静态不是全局的,它们是每个类加载器的全局。如果具有静态字段的类加载到不同的类加载器中,则其静态成员将不会在不同的类加载器中可见。

Statics are not global per JVM, they are global per classloader. If the class with the static field is loaded in a different classloader, its static members won't be visible within a different classloader.

如何部署项目A和项目B ?它们是否在同一个类加载器中?

How are project A and project B deployed? Are they in the same classloader?

我不熟悉servicemix,但我想它会在单独的类加载器中部署单独的应用程序,就像Java EE应用程序将在不同的应用程序中部署不同版本的classloaders,所以你可以并排运行app 1.0和app 1.1,它们不会相互影响。

I'm not familiar with servicemix, but I imagine it deploys separate apps in separate classloaders, just like a Java EE app will deploy different versions of the same app in different classloaders, so you can run app 1.0 and app 1.1 side-by-side, and they won't affect each other.

这是设计的。

如果是这种情况,您需要一些独立的东西来维持共享状态。 (例如数据库)

If this is the case, you need something independent to maintain shared state. (e.g. a database)

这篇关于静态字段的范围是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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