需要帮助以避免类型转换

时间:2013-08-10 13:00:09

标签: java generics

我需要帮助重构以下代码。我想在此代码中修复两个主要问题 1. Rule1实现中的不安全类型转换 2.实现太多接口

  public interface Rule {
     public void execute(DataProvider dataProvider);
  }

  public interface DataProvider {
     // No common functions as of now 
  }

  public interface Rule1dataProvider extends DataProvider {
     // Functions required by Rule1
  }

  public class Rule1 implements Rule {
     public void execute(DataProvider dataProvider) {
       ADataProvider rule1DataProvider = <ADataProvider>dataProvider;
       // Other logic 
    }
  }

 public class EntityADataProvider implements Rule1DataProvider, Rule2DataProvider... {
    // Overrides functions of Rule 1 and Rule2 
 }

我试图在这里使用泛型,但无法找出使用它们的正确方法以消除类型转换

1 个答案:

答案 0 :(得分:4)

使规则通用:

public interface Rule<T extends DataProvider> {
    public void execute(T dataProvider);
}

然后

public class Rule1 implements Rule<Rule1dataProvider> {
    @Override
    public void execute(Rule1dataProvider dataProvider) {            
        // ...
    }
}