I want to instantiate two TCP server applications with the same basic method. These server classes use many static and stream local fields. Is it possible to load classes, as in another application domain?
this is my test case:
The tester class has simple getter and setter methods for setting a global static object.
public class Tester {
public Tester() {
System.out.println(getClass().getClassLoader());
}
public void setText(String text) {
GlobalObject.globalText = text;
}
public String getText() {
return GlobalObject.globalText;
}
}
This is a global object, accessible from anywhere. I want to restrict access to this object.
public class GlobalObject {
public static String globalText;
}
This is my test program.
public class Main {
public static void main(String[] args) {
Tester ta1 = new Tester();
ta1.setText("test");
System.out.println(ta1.getText());
Tester ta2 = new Tester();
System.out.println(ta2.getText());
CustomClassLoader ccl = new CustomClassLoader();
try {
Tester tb = (Tester) ccl.loadClass("Tester").newInstance();
System.out.println(tb.getText());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Conclusion:
sun.misc.Launcher$AppClassLoader@11b86e7
test
sun.misc.Launcher$AppClassLoader@11b86e7
test
sun.misc.Launcher$AppClassLoader@11b86e7
test
The result I want:
sun.misc.Launcher$AppClassLoader@11b86e7
test
sun.misc.Launcher$AppClassLoader@11b86e7
test
sun.misc.Launcher$AppClassLoader@1234567
null
source
share