Using classloader to highlight two static classes

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) {
    // Default class loader;
    Tester ta1 = new Tester();
    ta1.setText("test");
    System.out.println(ta1.getText());

    Tester ta2 = new Tester();
    System.out.println(ta2.getText());

    // Custom class loader;
    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
+3
source share
1 answer

You do not tell us that CustomClassLoader.

, .

. :

URL[] urls = new URL[] {new File("build/classes/").toURL()};
ClassLoader loader = new URLClassLoader(urls, null);

- .

+3

Source: https://habr.com/ru/post/1765091/


All Articles