Home > Software design >  Finding generic type in parallel hierarchies of generic types
Finding generic type in parallel hierarchies of generic types

Time:01-31

Imagine I have 3 rules : Rule<A>, Rule<B>, Rule<C> Same I have 3 datasources : Datasource<A>, Datasource<B>, Datasource<C>

If I have a list of rules : List<Rule<?>> and I do a stream : ruleList.stream().map(rule -> ...)

In the lambda function, I would like to call the datasource with same generic type than rule. For example :

ruleList.stream().map(rule -> {
   Class<T> ruleType = ... // Class<A>, Class<B> or Class<C>
   Datasource<T> datasource = datasourceResolver.resolve(ruleType); // Datasource<A>, Datasource<B> or Datasource<C>
   return datasource.doSomething();
})

What would be the code to retrieve the ruleType and the code of datasourceResolver ?

CodePudding user response:

Because of type erasure you'll need to take Rule and DataSource together (not logical) or:

class Rule<T> {
    public final Class<T> type;
    protected Rule(Class<T> type) {
        this.type = type;
    }
}

private Map<Class<?>, DataSource<?>> dataSourcesByType = New HashMap<>();

Now you can register DataSources by type

Class<?> ruleType = rule.type;
DataSource<?> ds = dataSourcesByType.get(ruleType);

You'll notice <?>, especially that ds cannot be more specific.

That could hint at alternative method overrides for cases A, B, C. A more type safe Map getter

public <X> DataSource<X> get(Class<X> type)
  • Related