This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
How can I obtain an Object instance from a 'Class' loaded by a custom class loader. I understand 'ClassCastException' in the output. Do I have any option or go via 'Reflection' route? Thanks Achit
Output :C:\>java MyClassLoader Class loader for MyClassLoader:sun.misc.Launcher$AppClassLoader@12f6684 This is fun Instance class loader:MyClassLoader@360be0 Class class loader:MyClassLoader@360be0 java.lang.ClassCastException at MyClassLoader.main(MyClassLoader.java:68) Some error
-----------------------------------<br />"Life is game,Cricket is serious."<br />-----------------------------------
Normally, if you know the exact name of a class at compile time, there isn't much of a reason to load that class via a custom class loader and then also via the system class loader, as you've done here. The ClassCastException is due to your trying to cast the instance loaded by the custom loader to the class loaded by the system class loader, which doesn't work as they're effectively two separate classes. The much more common situation is that there's an interface, and you want to use a custom loader to load a class that implements that interface, while the interface class itself is loaded by the system class loader. Then you'll have no trouble casting the object to the interface type and calling its methods. Make sense?
Hi Ernest In the common scenario where people use Interfaces and then it would not give ClassCastException as you say. Now, is the reason for that is, - When we have an object that implements interface and we try to cast it to interface type then the JVM just sees if the object implements (or extends in a way??) that interface or not hence different classloader types don't matter.. Am I right? Regards Maulin
Joined: Nov 04, 2001
hello? renewing timestamp...
Joined: Apr 19, 2002
Thanks guys, It was a mistake(misunderstood concept!!) on my part. I understand class laoded form different class loaders are not same. Even if they have the same name and loaded from the same location.Thats why I wrote in my initial post.
I understand 'ClassCastException' in the output
I assumed since the class is loaded by MyClassLoaded JVM will use same class def. Which is not the case. I figured it out later. Thanks again for you help. Achit
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com