KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I'm experimenting with using different classloaders to load a particular class, and see if the static variables in that class can have different instances. Basically, I'm trying to write code for what Stephen C has mentioned in this answer . Here are my classes: CustomClassLoader.java class CustomClassLoader extends ClassLoader { public Class loadClass(String classname) throws ClassNotFoundException { return super.loadClass(classname, true); } } Test.java (which contains the driver) class Test { public static void main(String[] args) throws Exception { CustomClassLoader c1 = new CustomClassLoader(); CustomClassLoader c2 = new CustomClassLoader(); Class m1, m2; m1 = c1.loadClass("A"); m2 = c2.loadClass("A"); m1.getField("b").set(null, 10); System.out.println(m1.getField("b").get(null)); System.out.println(m2.getField("b").get(null)); } } A.java (which contains the static variable) class A { public static int b = 5; } When I run the Test class, I get the following output: $ java Test 10 10 I expected the output to be 10 and 5. How can I make the code create two instances of my static variable? Note: I'm doing this only for experimentation and learning - but I'd be interested to know if there could be any real world application of this.
Tags (comma-separated)
Save Edits
Cancel