I am wondering if it is possible to accomplish the following using EJB3.
I have the following interface:
interface DateParser {
Date parseDate(String input);
String getType();
}
Then I have several implementations of said interface that handle different formats based on the information given in the getType method. When my bean starts up it creates a Set of implementations of DateParser and when it needs to parse a date, it iterates over the set to see which one matches. If one matches it uses that one to parse the date. If none match, then it applies a default strategy. I would like to get away from instantiating these delegates because every time I add a new strategy it requires a code change in the bean making it a huge mess.
I would much prefer to have the container inject all of the implementations it finds at deployment. Is there a reasonable way to accomplish this?
Thanks
Implementation of this interface should be regular classes, not beans. EJB are meant to be business services. Parsing date is IMHO a responsabiltiy that is too fine-grained for a bean.
I don’t think there is standard way to do that. I see only two options to dynamically fill the set with the instances:
Use an external configuration files with list of class names. Reach each class name and instantiate one instance reflectively (Class.forName, Class.newInstance). Then add it to the set.
Iterate over all classes in the class path, identifiy those that are implementation of
DateParser. Then instantiate it reflectively, and add it to the set. Note that iterating over loadable classes is kind of tricky, see this answer.That should require a code change in a class, but not the bean itself. The bean should delegate the creation of the set, the identification of the parser, etc. to another class, IMHO.