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

基于某人编写的现有架构,我需要扩展我的实现。让我用一个示例代码来解释:


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

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


紫衣仙女
浏览 87回答 3
3回答

开心每一天1111

BaseConfiguration如果对象实例通过instanceof检查,您可以在转换为之后调用它:if (o instanceof BaseConfiguration) {&nbsp; ((BaseConfiguration) o).clone(someDictionary, Foo.class);} else {&nbsp; &nbsp;throw new AssertionError("Does not extend BaseConfiguration");}

慕村9548890

如果所有配置都应该是可克隆的,只需将其添加到Configuration.如果不是全部 - 做类似的事情interface CloneableConfiguration extends Configuration {&nbsp; &nbsp; public <T> T clone(Dictionary<String, Object> properties, Class<T> clazz);}然后public class XMLConfiguration extends BaseConfiguration implements CloneableConfiguration {&nbsp; &nbsp; ...}但永远不要在你的陈述中使用具体的实现。

哈士奇WWW

投射你的Configuration对象。由于 API 不在您手中,因此请使用instanceof安全检查Configuration conf = ConfigurationAdmin.getConfiguration();if(conf instanceof BaseConfiguration) {&nbsp; &nbsp; BaseConfiguration base = (BaseConfiguration) conf;&nbsp; &nbsp; base.clone();}else {&nbsp; &nbsp; // throw an exception of log an error}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java