简体   繁体   中英

Dynamic class loading for url dispatching in Java

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM