是否可能有多个静态变量实例 [英] is it possible to have multiple instances of static variables

查看:256
本文介绍了是否可能有多个静态变量实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

静态变量只有实例(即它们是类的一部分)。
ex:Math.pi



有没有办法可以有多个静态变量实例?
我听说有与类加载器有关的东西吗?

解决方案

如果你发现需要多个静态变量实例,这是一个强烈的迹象,表明您不应该首先使用静态变量。



是的,如果在不同的类加载器中加载相同的类,则每个副本该课程将有自己的静态。但是,唯一可以静态引用这些静态的代码将是由同一个类加载器加载的类。当然,该代码只会(静态地)在类的一个副本中看到静态。所以你可能还没有取得很多成就。



你应该重构你的代码以将静态变量转换为实例变量。



不要乱用类加载器。

>

Static variables have only instance (that is they are part of the class). ex: Math.pi

Is there any way there could be multiple instances of static variables? I heard there is something related to Classloaders?

解决方案

If you find that you need multiple instances of a static variable, this is a strong indication that you should not be using static variables in the first place.

Yes, if the same class is loaded in different class loaders, then each copy of the class will have its own statics. However, the only code that can refer statically to those statics will be classes loaded by the same class loader. And of course, that code will only (statically) see the statics in one copy of the class. So you probably haven't achieved a lot.

Rather than messing around with classloaders, you should be refactoring your code to turn the static variables into instance variables.

这篇关于是否可能有多个静态变量实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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