This is a follow up to java.net package - Override UDP transport. I am raising a new question here because I am trying a different approach to the problem. I have gone through simlar questions
java custom classloader: some classes are not loaded by my classloader
How to set my ClassLoader as the JVM's ClassLoader for loading ALL classes (jar classes included)?
but no luck. so here is the problem.
I am trying to intercept loading of all classes (including standard JDK classes) in my custom class loader. The idea is to load an extended class whenever there is a request for DatagramSocket class. I dont have a handle to when and how DatagramSocket would be instantiated in the application and hence I thought this is the best way to intercept loading of this particular class before I start the app from my main method. For this purpose I wrote TestClassLoader,
public class MyClassLoader extends ClassLoader
{
public MyClassLoader(ClassLoader parent)
{
super(parent);
}
public Class loadClass(String name) throws ClassNotFoundException
{
System.out.println("loading " + name);
if (name.equals("java.net.DatagramSocket")
|| name.equals("MyDatagramSocket"))
{
System.out.println("Loading DatagramSocket class.... " + name);
return super.loadClass("MyDatagramSocket");
}
else
{
return super.loadClass(name);
}
}
}
and a test program,
public class TestClassLoader
{
public static void main(String[] args) throws Exception {
//See if this invokes myClassLoader
DatagramSocket dSocket=new DatagramSocket();
System.out.println("DatagramSocket.classloader = "+DatagramSocket.class.getClassLoader());
//check the Class loader for the main class
System.out.println("TestClassLoader.classloader = " + TestClassLoader.class.getClassLoader() );
}
}
and invoked the test program using "-Djava.system.class.loader=MyClassLoader" option. The output I see is
loading java.lang.System
loading java.nio.charset.Charset
loading java.lang.String
loading TestClassLoader
DatagramSocket.classloader = null
TestClassLoader.classloader = sun.misc.Launcher$AppClassLoader@130c19b
I dont see my test class loader being called when DatagramSocket is initialized. Am I doing this right ?