同EAR中WAR修改JAR静态字段后另一WAR不受影响的原因问询
Great question! This behavior makes total sense once you unpack how WebLogic handles class loading for web applications, plus how Java's static fields are tied to class instances. Let’s break down the key reasons:
1. WebLogic Isolates WARs with Separate Class Loaders
WebLogic (like most Java EE app servers) uses a class loader hierarchy with WAR-level isolation. When you place JAR1 in both WAR1/WEB-INF/lib and WAR2/WEB-INF/lib, here’s what happens:
- WAR1 gets its own dedicated class loader that loads the JAR1 from its own
WEB-INF/libdirectory, creating a uniqueCLASS1Class object. - WAR2 gets a completely separate class loader that loads its own copy of JAR1, creating an entirely distinct
CLASS1Class object.
Even though these two CLASS1 types have the same fully qualified name, the JVM treats them as different classes because they were loaded by different class loaders.
2. Static Fields Belong to the Class Object, Not the Class Name
In Java, static fields are not "global" across the entire JVM—they’re tied directly to the Class instance that represents the loaded class. Since WAR1 and WAR2 have separate CLASS1 Class objects:
- When your
ModServicein WAR1 uses reflection to updateSTATIC1, it’s only modifying the static field on WAR1’sCLASS1instance. - WAR2 continues to use its own
CLASS1instance’sSTATIC1field, which still holds the default"DEFAULT_VAL"value.
3. Quick Way to Verify This
If you want to confirm this is what’s happening, add a quick debug log in both WARs:
// In WAR1's code System.out.println("WAR1 CLASS1 ClassLoader: " + CLASS1.class.getClassLoader()); System.out.println("WAR1 CLASS1 Instance: " + CLASS1.class); // In WAR2's code System.out.println("WAR2 CLASS1 ClassLoader: " + CLASS1.class.getClassLoader()); System.out.println("WAR2 CLASS1 Instance: " + CLASS1.class);
When you run both apps, you’ll see the ClassLoader and Class instance hash codes are different between the two WARs—proof they’re separate entities.
4. This Is Intentional Design
This isolation isn’t a bug—it’s a feature! Java EE servers do this to:
- Prevent version conflicts: If WAR1 needed JAR1 v1 and WAR2 needed JAR1 v2, they could run side-by-side without issues.
- Keep applications independent: Changes in one app (like your static field modification) can’t accidentally break another app running on the same server.
内容的提问来源于stack exchange,提问作者Anand Rockzz

