Java中静态字段的确切含义是什么? [英] What is the exact meaning of static fields in Java?

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

问题描述

我想在同一个类的各种对象实例之间共享一个对象。

I would like to share an object between various instances of objects of the same class.

从概念上讲,当我的程序运行时,A类的所有对象都可以访问B类的同一个对象。

Conceptually, while my program is running, all the objects of class A access the same object of class B.

我看到 static 是系统范围的,它的用法是泄气。这是否意味着如果我在实例化A类对象的同一JVM上运行另一个程序,这些对象可能会访问与前一个程序中访问的对象相同的B对象?

I've seen that static is system-wide and that its usage is discouraged. Does that mean that if I've got another program running on the same JVM that instantiates objects of class A, these objects could potentially access the same B object as the one accessed in the previous program?

使用静态字段背后的缺点通常是什么?

What are generally the flaws behind using static fields?

是否有任何替代方案(不需要大量实施)?

Are there any alternatives (that do not require a huge effort of implementation)?

推荐答案

静态并不意味着由所有实例共享 - 它意味着根本不与特定实例相关。换句话说,你可以在没有创建任何实例的情况下进入A类的静态字段。

Static doesn't quite mean "shared by all instances" - it means "not related to a particular instance at all". In other words, you could get at the static field in class A without ever creating any instances.

至于在同一个程序中运行两个程序JVM - 它实际上取决于运行两个程序的确切含义。静态字段有效与类对象相关联,而类对象又与类加载器相关联。因此,如果这两个程序使用单独的类加载器实例,那么您将拥有两个独立的静态变量。如果他们都使用相同的类加载器,那么只有一个,所以他们会看到彼此的变化。

As for running two programs within the same JVM - it really depends on exactly what you mean by "running two programs". The static field is effectively associated with the class object, which is in turn associated with a classloader. So if these two programs use separate classloader instances, you'll have two independent static variables. If they both use the same classloader, then there'll only be one so they'll see each other's changes.

至于替代方案 - 有各种选择。一种方法是将对共享对象的引用传递给您创建的每个需要它的对象的构造函数。然后它需要存储该引用以供日后使用。这可能有点痛苦并且比静态方法吸收更多内存,但它确实易于测试。

As for an alternative - there are various options. One is to pass the reference to the "shared" object to the constructor of each object you create which needs it. It will then need to store that reference for later. This can be a bit of a pain and suck up a bit more memory than a static approach, but it does make for easy testability.

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

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