tags:

views:

52

answers:

2

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?

A: 

Well the whole point of a static variable is a variable that exists as part of the class and not the objects created. That said I don't think you can have multiple instances of a static variable within a class.

Glenn Nelson
+5  A: 

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.

Stephen C
So, how can I code to use multiple classloaders?
Satish
@satish - so I haven't convinced you that it is a bad idea?
Stephen C
the point was not about bad-idea, but trying to understand the idea behind the multiple-classloaders. do point me to any tutorials or examples if you come across any. Thanks for the great answer :-)
Satish
http://www.oracle.com/technetwork/articles/javase/classloaders-140370.html
Stephen C