Friends,
I was obsessed with custom class loaders in Java because I faced a real issue while working on the project. The JAX-WS implementation would work on one App Server where the same code would fail on the other. I knew it could be because of Classloaders and how different vendors of App server implement features documented in Specs.
Well, after little reading I realized how a premitive Class loader can be written. Idea was to load a class using custom class loader and test if the same is really loaded using my class loader or by system class loader. If the the class we are trying to load is in classpath, then it gets loaded by system class loader by default and I did not really understand how not to keep my class on the class path and then load it using custom class loader.
I decided to load a class from a random directory which is NOT in the class path. Now I would load the class bytes from the class file for my class but would fail for java.lang.Object. As we all know, every class in Java is child of java.lang.Object :-) Now my class loader would fail because it could not find the class file for java.lang.Object at the specified location. After careful analysis I realized where the mistake was. I was trying to load all the classes (including system classes) using my custom class loader. Then I changed the approach to:
- Check if the class is already loaded by custom class loader in the cache.
- If not already loaded, use System class loader to load it for you.
- If System class loader can not load it, then use our custom logic to load the byte codes from the generated .class file
- Define and return the loaded class
This is "System class loader first" approach, where is I check if system class loader can load the class for me and use my custom class loader only if it fails to load.
Java also has Class loader hierarchy, which needs to be looked at. The behavious depends upon which method/s we override while extending java.lang.ClassLoader. I still have to look into it.
I managed to get my custom class loader working and also tested with a sample program. I will post it here once the cleanup is done.
Till then, take care.
- Manoj
No comments:
Post a Comment