Puzzling issue in casting a class

G

GaryM

Recently I asked the question on how to initialize a web app. The
advice I adpoted till I could learn a better approach was to declare
web.xml servlet that loads on startup.

I was browsing the Jetty API Doc and I noticed the class
WebApplicationContext inherits a loadclass method:

Class loadClass(String class)

To test it out I tried loading my intialization servlet as follows:

WebApplicationContext wac = new WebApplicationContext( ... );
Class class = wac.loadClass("InitializerServlet");
HttpServlet servlet = (HttpServlet) class.newInstance();
servlet.init();

And this worked fine. However there is no longer any need for that
class to be a servlet, so I changed it accordingly (i.e. removed the
'extends HttpServlet'). Changed the above lines accordingly
(HttpServer became Initializer). Immediately got a
ClassCastException. Created a constructor with a debug message and
saw that Initializer was being constructed. But it failed on the
casting line.

In the end I thought of a number of reasons why the approach was
unsound and since have moved on, but I am still wondering why the
heck I could not cast that instance as itself.

If someone could inch my java knowledge on a bit, would be most
grateful.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top