Search code examples
javaclassloaderstatic-variables

Will other instances of a class be able to access a static variable in another?


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));

Solution

  • 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.)