Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 227
  • Last Modified:

Dynamically load classes with servlets

Hi all,
A variable is based to my servlet and a lookup is preformed in the database. Depending on what this variable is a class is loaded. I've written an abstract to handle all this. When I was testing I didn't use a servlet initially but instead wrote a main and tested on the command line to make sure the lookup and creation was working. This test file began with:
public class TestUser extends DecisionCreator
      {
      public static void main(String args[])
            {
etc...

Where DecisonCreator is:
public abstract class DecisionCreator
{
                protected static Decision createDecision(String name) throws DecisionNotCreatedException
      {
      Decision myDecision;
      try
            {
            Class DecisionClass = Class.forName(name);
            myDecision = (Decision) DecisionClass.newInstance();
            }
                //omitted catches
      return myDecision;
      }
Decision is a simple interface:
public interface Decision
      {            
      String[] launch(String user);
      }
When I went to put use my code in the servlet I came up against this problem. My servlet is called Link:
public class Link extends HttpServlet
I cannot extend DecisionCreator as I did in my test file. Is there a solution to this or do I have to re-design everything?
If anything is not clear please let me know

Thanks,
Shane
0
fast74
Asked:
fast74
  • 2
  • 2
1 Solution
 
girionisCommented:
 Call the TestUser class from your Servlet and let it (the TestUser) do the loading of the classes.
0
 
girionisCommented:
 For instance:

MyServlet extends HttpServlet
{
  public void doPost(...)
  {
      if (value read from db == something)
      {
           TestUser tu = new TestUser();
           tu.loadClass(something);
           ...
      }
  }
}
0
 
TimYatesCommented:
yeah incorporate an instance, don't try to extend :-)
0
 
Mayank SAssociate Director - Product EngineeringCommented:
If you want to do it without TestUser, then do you necessarily need to make the DecisionCreater class as abstract? If not, then you can use its instance....
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Accept girinois' comment as answer.
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now