Multiple instances of static variables

前端 未结 4 1305
自闭症患者
自闭症患者 2021-02-13 14:42

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,

4条回答
  •  深忆病人
    2021-02-13 15:39

    I had the same problem (integration tests) and tried it with @Michael Borgwardt approach. Here some example code:

    URLClassLoader classLoader1 = new URLClassLoader(new URL[]{new URL("file:///path/to/jar/my-classes.jar")}, null);
    URLClassLoader classLoader2 = new URLClassLoader(new URL[]{new URL("file:///path/to/jar/my-classes.jar")}, null);
    
    // Load with classLoader1
    Class myClass1 = classLoader1.loadClass("MyClass");
    Constructor constructor1 = myClass1.getConstructor();
    Object instance1 = constructor1.newInstance();
    
    // Load with classLoader2
    Class myClass2 = classLoader2.loadClass("MyClass");
    Constructor constructor2 = myClass2.getConstructor();
    Object instance2 = constructor2.newInstance();
    
    // Load with system classloader
    MyClass myClass = new MyClass();
    
    // ...
    

提交回复
热议问题