Here is an interesting example to use URLClassLoader to cause a Class object be loaded 3 times into JVM
// StaticTestClassLoader.java
// --------------------------
import java.io.*;
import java.net.*;
/**
* Load the same Class (with static var as counter ) into three separate ClassLoaders.
* make sure your subdir is not in your CLASSPATH
* and Dummy.class is sitting in it*/
public class StaticTestClassLoader {
public static void main (
String args[]) throws Exception {
URL[] url = { new File("subdir").toURL() };
URLClassLoader cl1 = new URLClassLoader(url);
URLClassLoader cl2 = new URLClassLoader(url);
URLClassLoader cl3 = new URLClassLoader(url);
cl1.loadClass("Dummy").newInstance();
cl2.loadClass("Dummy").newInstance();
cl3.loadClass("Dummy").newInstance();
}
}
// here is the Dummy.java
public class Dummy{
public static int staticCount = 0;
public Dummy(){
staticCount++;
System.out.println("Instance #" + staticCount + "constructed.");
}
}
Roseanne