0

I’m working on a project that has a series of “Rule” classes (CustomerRule, VolumeRule, TimeRule, etc.). These classes are auto-generated and shouldn’t be modified from their generated form.

To process these rules, I have a series of “RuleProcessor” classes (CustomerRuleProcessor, VolumeRuleProcessor, etc.) that implement the following interface:

public interface RuleProcessor<T extends Rule> {
   T apply(T rule, EvaluationInput input);
}

With an implementation looking like this:

public class CustomerRuleProcessor implements RuleProcessor<CustomerRule> {...}

Finally, the rule classes themselves are grouped together and stored as JSON in the DB. So there could be multiple rules of different types stored together to be processed as one group. When retrieved, I’ll have a List<? extends Rule> that will be streamed and processed.

My question is this:

  • Given a concrete class (for example, CustomerRule), is there a way to find the processing class that implements the RuleProcessor<CustomerRule> interface?

I know I could just use the naming convention and use class.getName() + "Processor". But I’m wondering if there’s a better, more elegant solution.

deduper
  • 1,944
  • 9
  • 22
pconrey
  • 5,805
  • 7
  • 29
  • 38
  • 1
    Type erasure leads to the result that the generic type isn't present at runtime anymore. You could store the rules not as a list but as a map of rule-name mapping to rule and find a rule by name then. – Smutje Oct 07 '20 at 15:15
  • My advice would be to use ImageIO as an example of how to do this. ImageIO effectively registers readers and writers for different Image Formats so that they can be discovered at Runtime. This is basically the pattern I think you should follow – ControlAltDel Oct 07 '20 at 15:21
  • 2
    @ControlAltDel The ImageIO registry is actually a copy of the more general SPI jar model, which can be implemented using [java.util.ServiceLoader](https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/util/ServiceLoader.html). – VGR Oct 07 '20 at 17:35

0 Answers0