There are three exceptions that you will get using BOF that you need to understand.
- ClassCastException
- ClassNotFoundException
- NoClassDefFoundError
2 and 3 are similar and can be treated together for our purposes.
There is a fourth – java.lang.VerifyError. If you get this you are in a world of pain. Don’t call me – I don’t know you.
You have been testing successfully in IntelliJ or Eclipse and then you deploy to the docbase and all of a sudden you get an exception! What happened? This is almost certainly a consequence of the different class loader setups.
Class cast exceptions occur when you attempt to cast an object to an interface (or class) that it does not implement, but there is a trick. Java considers a class to be the same when it has the same fully qualified name (including the package name) and it is loaded by the same class loader. So x.y.Z loaded by one class loader is not the same as x.y.Z loaded by another class loader, and any attempt to cast will result in a ClassCastException.
How is this relevant to BOF? Imagine, by accident, you packaged x.y.IZ (your module’s interface) in your implementation jar instead of or in addition to your interface jar. Now your module’s class loader is “parent last”, so x.y.IZ will resolve to the interface from your module class loader. Now after the module is instantiated, you will attempt to cast it to x.y.IZ loaded in your application class loader – ClassCastException, even though an inspection of the source will leave you scratching your head.
How about a ClassNotFoundException? Possibly the class is just missing from your jars altogether. This will most often occur with your primary class.
NoClassDefFoundError can be even trickier. Imagine you accidently packaged an implementation class which is referenced by your primary class in an interface jar. Now when the primary class is loaded it will not find it in your module class loader, but the search will then move on to the interface class loader and the class will be found. Now imagine that class refers to another – the search for this new class starts at the interface class loader (the parent of the module class loader) and you can’t see classes in child class loaders so that second class will not be found. Typically this will manifest as a NoClassDefFoundError.
There is no substitute to understanding the BOF class loaders and behaviors to debug these problems. I wish it weren’t so, but it is. So take some time to familiarize yourself with these details and be very diligent when packaging your jars – this is the best defense.
0 responses so far ↓
There are no comments yet...Kick things off by filling out the form below.