Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

java - is it possible to have multiple instances of static variables

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...