1

I am experimenting with a little framework where I have a bunch of actions defined in classes. I want to write a url dispatcher that will call the relevant action based on matching a url pattern specified in the action class. I want to avoid making a redundant list of all the available actions in the dispatcher class itself, and rather have it load instances of the actions dynamically on program start.

I initially figured I could put all these actions in a specific package, then have my dispatcher search that package for all classes that implement the action interface and load them into a list of action instances that are ready to be called.

From my googling I have discovered that there doesn't seem to be a way to actually get a list of classes that exist in a package (due to how classes are capable of being loaded in many different ways).

So my question: is this actually possible and how would I go about it? But maybe that is even too much to ask, is this even a good idea? What are other approaches that I could take, and are there any other examples of people doing dynamic dispatching to classes in java?

leafo
  • 1,862
  • 14
  • 18
  • I am not sure if you're talking about this in the servlet context (necessary tags are completely missing and there's much ambiguity in your question), so here's just a dumb comment with a link instead of a fullfledged answer: [Design patterns in Java web applications](http://stackoverflow.com/questions/3541077/design-patterns-web-based-applications). You may find it useful. – BalusC Sep 15 '10 at 20:01
  • I left it ambiguous on purpose I suppose. The context really doesn't matter as much as how code can be dynamically loaded at runtime. I am not concerned about separating logic, rather how can I dispatch some arbitrary command (say a string containing a url, as my example from the question) to the proper class that contains the implementation of the desired action. I guess a closer analogy (I think) would be a servlet container rather than a servlet itself. – leafo Sep 15 '10 at 21:05

1 Answers1

0

I am not sure that I am understanding the question completely, due to its ambiguity, but this sounds quite similar to what Java Servlets already do. Doesn't it?

@WebServlet(name = "Action1",urlPatterns = {"/actions/Action1"})
public class SampleServlet extends HttpServlet {
   //...
}

Wouldn't that work for you?

Alternatively, you could use a library like Google Reflections to discover all your annotated classes:

@Action(url="/actions/one.do")
class MyAction {

    public void execute(){
        //..
    }
}

For example:

Reflections reflections = new Reflections("com.jedi.academy");
Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(Action.class);

This would get me a set containing MyAction.class.

Edwin Dalorzo
  • 76,803
  • 25
  • 144
  • 205