The obvious cause for ClassCastException is that you try to cast from one class to another class but the other class is not a parent of the class you try to cast, but there are other cases in which ClassCastException can happen:
AClass aObject = (AClass) bObject;
- bObject doesn't inherit from AClass or it doesn't AClass instance.
- bObject inherit from AClass or it is AClass instance, however bObject was loaded by a different class loader, In this case the JVM consider bObject as a different class, the solution is to load AClass only in one of the class loaders, the same class shouldn't be loaded by two different class loaders.
For example:
Object a1 = new A(); // Load by classLoader x
Object a2 = new A(); // Load by classLoader y
a1 = (A) a2; // Would throw ClassCastException
Showing posts with label ClassLoader. Show all posts
Showing posts with label ClassLoader. Show all posts
Tuesday, December 11, 2007
ClassCastException Solution
Posted by
blogger
at
10:54 PM
0
comments
Labels: ClassCastException, ClassLoader, JBM, Solution
ClassNotFoundException Solution
Here is a list of possible problems which would may case ClassNotFoundException and the solution for this problems
- The class doesn't exists in the classpath, You can add it to your classpath by either click on properties of the project and add it to the java build path or you can choose run->classpath->and add the jar.
- The class exists in the classpath, but it has a static section in the beginning of the class which throws an exception in this case the class doesn't create by the classloader, the solution is to fix the exception thrown in the static section or add try catch.
- The class exists but it is loaded by a different classloader, for example you have two EAR files in which one need to access another one, The solution is to add reference between this two EAR files, or making one of the class loaders be the parent of the other class loader
Posted by
blogger
at
4:24 AM
0
comments
Labels: ClassLoader, ClassNotFoundException, Exception, Solution, Solve
Subscribe to:
Posts (Atom)
