Suppose I have a generic class that I use which declared like this:
public class ConfigurableRuleKey<R extends Configurable & Rule> extends Key<R> {
private final R rule
public ConfigurableRuleKey(R rule) {
this.rule = rule;
}
/* Additional methods are declared here */
}
And I want to implement a factory method that checks if passed rule implements interface Configurable, when create configurable rule or just create a basic key:
public static <R extends Rule> Key<R> create(R rule) {
if (rule instanceof Configurable) {
return new ConfigurableRuleKey<>(rule); //This will not compile
} else {
return new RuleKey<>(rule);
}
}
The problem is that in my factory method I can't pass rule to constructor of ConfigurableRuleKey because it doesn't fit the declared generic constraints (event if I'd explicitly checked that it implements Configurable). The question is how can I cast my rule instance so it will fit the constructor restrictions in ConfigurableRuleKey?