I have a class that I know will be loaded by a URLClassLoader for each instance of it, so if I have a static variable in one, will the other instances be able to access it?
For example, Class MyClass is loaded by ClassLoader A and ClassLoader B, 开发者_如何学运维and I want to know if MyClass loaded by A will have the same static fields as MyClass loaded by B.
So basically, will the following statement always be true:
A.loadClass("MyClass").getField("MyField").get(null).equals(B.loadClass("MyClass").getField("MyField").get(null));
Static variables are unique across classloaders. (The references to these that is) The values might be the same. Using equals will work, using == will not.
EDIT: Each ClassLoader will load a different class (They can even be different versions). The initialized statics will be different. Two different classes from different ClassLoaders can have variables (static or not) that are identical in value.
Unfortunately @Dinesh/@DAJ's answer is incorrect. (@Romain's maybe too, but the wording is hard to parse.)
Suppose you have a class a.b.C
and you arrange that the same class gets loaded by two different classloaders. According to the specifications, you will end up with two distinct Class
objects with the fully qualified name a.b.C
, and from the type system perspective two distinct types. Each of the types will have a different set of static variables.
The primary reference for this is JLS 4.3.4 - paragraphs 2 and 3.
You can infer that each reference type that is distinct (at runtime) will have a distinct set of statics from JLS 4.12.3, JLS 8.3.1.1, JLS 12.4, and other parts of the language spec.
So basically, will the following statement always be true:
A.loadClass("MyClass").getField("myField").get(null)
.equals(B.loadClass("MyClass").getField("myField").get(null));
In general it won't.
It will always be true in some cases, depending on how MyClass
initializes myField
. For instance, if the field is initialized to a literal String, then it will.
(The trick to observing this is to arrange that MyClass
is actually loaded by the two classloaders A
and B
, and not by a common ancestor classloader.)
AFAIK, it shouldn't matter who loads the class. As long as the fields are static, they should be the same. Did you try to experiment with some code?
精彩评论