Why do I get class loading errors from JSPs or servlets when the EJB Container is running in-process?

From Support
Jump to: navigation, search
Why do I get class loading errors from JSPs or servlets when the EJB Container is running in-process?

The problem has to do with class loaders. As you may already know, your JSPs, Servlets, and your EJBs run in custom class loaders. This is what allows you to dynamically install a new Servlet or EJB to a running VM and have this new code run dynamically.

Unfortunately, writing code which can run correctly in a class-loaded environment is a little different than writing normal code. However, the good news is that, if you write code which can run in a class loader, then this code will also run in a normal environment.

There is basically one rule to follow, when running in a class loader: always load your classes with respect to another class-loaded class. Simply put, this means you cannot do the following:

Class c = Class.forName(className); Instead, you need to do the following:

Class c = someClass.getClassLoader().loadClass(className); where "someClass" is a class which was itself class loaded. Typically, this means your own class:

Class c = this.getClass().getClassLoader().loadClass(className); Or, if you are running in a static method of class Foo:

Class c = Foo.class.getClassLoader().loadClass(className); So, why do you have to jump through these hoops to get a class? The answer is that two classes, loaded by different class loaders (or more typically, one loaded by a custom class loader and one loaded by the default system class loader), are not the same type to the Java VM.

Also, problems can occur with the use of the MetaData. Here, we are returning instances of classes, where it may not be the case that these classes are the right ones with respect to your Servlet's class loader. To avoid this problem, you could try:

Class homeClass = this.getClass().getClassLoader(). loadClass(ejbMetaData.getHomeInterfaceClass().getName());  



Article originally contributed by Borland Developer Support