接口没有抽象类时,访问抽象方法的最佳方法是什么?

时间:2019-06-03 15:49:22

标签: java interface

基于某人编写的现有体系结构,我需要扩展实现。让我用示例代码进行解释:

interface Configuration{
   public String getPID();
   public void display(); 
}

public abstract class BaseConfiguration implements Configuration {
     @Override
     public String getPID(){
          //some code here
     }
     @Override
     public void display(){
          //some code here
     }

     abstract public <T> T clone(Dictionary<String, Object> properties, 
      Class<T> clazz);
}


public class XMLConfiguration extends BaseConfiguration{
    public <T> T clone(Dictionary<String, Object> properties, 
      Class<T> clazz){
      // implementation  
     }
}

public class ConfigurationAdmin
{
     public static Configuration getCondfiguration(){
        return new XMLConfiguration();
     }
}

我了解无法从界面调用clone方法。

Configuration conf = ConfigurationAdmin.getConfiguration();
conf.clone(someDictionary, Foo.class) // Gives compilation error

调用克隆方法的最佳方法是什么?

3 个答案:

答案 0 :(得分:4)

如果对象实例通过了BaseConfiguration检查,则可以在强制转换为instanceof后调用它:

if (o instanceof BaseConfiguration) {
  ((BaseConfiguration) o).clone(someDictionary, Foo.class);
} else {
   throw new AssertionError("Does not extend BaseConfiguration");
}

答案 1 :(得分:1)

如果所有配置都是可克隆的,只需将其添加到Configuration

如果不是全部-做类似的事情

interface CloneableConfiguration extends Configuration {
    public <T> T clone(Dictionary<String, Object> properties, Class<T> clazz);
}

然后

public class XMLConfiguration extends BaseConfiguration implements CloneableConfiguration {
    ...
}

但是切勿在语句中使用具体的实现。

答案 2 :(得分:0)

投射您的Configuration对象。由于API不在您手中,请使用instanceof检查安全性

Configuration conf = ConfigurationAdmin.getConfiguration();
if(conf instanceof BaseConfiguration) {
    BaseConfiguration base = (BaseConfiguration) conf;
    base.clone();
}
else {
    // throw an exception of log an error
}