接口java的问题

时间:2013-11-14 11:59:40

标签: java interface casting jaxb

我在java中使用接口时遇到问题。我将向您展示更明确的代码:

我使用jaxb从XML配置文件中提取数据:

public class LoadFilePollerConfiguration implements IConfig{

    File configFile = new File("config.xml");

    @Override
    public void loadConfiguration() throws Exception  {
        // TODO Auto-generated method stub
        loadFilePollerConfiguration();
    }

    private void loadFilePollerConfiguration() throws Exception{
        // TODO Auto-generated method stub
        SchemaFactory sf = SchemaFactory.newInstance
                (XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(new File("config.xsd"));
        JAXBContext jc = JAXBContext.newInstance(FilePollerConfiguration.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        unmarshaller.setSchema(schema);
        unmarshaller.setEventHandler(new MyValidationEventHandler());
        FilePollerConfiguration f = (FilePollerConfiguration)
                unmarshaller.unmarshal(configFile);

        Marshaller mar = jc.createMarshaller();
        mar.marshal(f, new File("test.xml"));

    }

}

我将向您展示IConfig界面:

public interface IConfig {

    public void loadConfiguration() throws Exception;

}

我有一个用于轮询存储库的类,我在我的主程序中使用了这个函数,这让我有些麻烦:

public class WatchSer {    

    private final WatchService watcher;     
    private final Map<WatchKey,Path> keys;          
    private boolean trace = false;  
    private FilePollerConfiguration configuration;

    WatchSer(IConfig conf) throws IOException {    

        this.watcher = FileSystems.getDefault().newWatchService();         
        this.keys = new HashMap<WatchKey,Path>();   
        configuration = (FilePollerConfiguration) conf;

    }

    public ArrayList<IConfig> getAction(File file, String Event) {

        Pattern p;

        for(int i = 0; i < configuration.directoriesList.size(); i++){
            p =  Pattern.compile(configuration
                              .directoriesList.get(i).toString());
            System.out.println(p);

        }

        return null;

    }

}

最后主要是谁实例化loadFilePollerConfiguration类,使用loadConfiguration()。直到这里,它'但是当我想创建一个WatchSer时,我有一个演员问题:

&GT;

public class Main {

    /**
     * @param args
     * @throws Exception 
     */

    public static void main(String[] args) throws Exception{
        // TODO Auto-generated method stub
        LoadFilePollerConfiguration l = new LoadFilePollerConfiguration();
        l.loadConfiguration();
        WatchSer w = new WatchSer(l);
        w.getAction(new File("C://Users//jmoreau040612
                    //Desktop//New//yop.xml"),  "create");
    }

}

线程“main”中的异常java.lang.ClassCastException:无法将LoadFilePollerConfiguration强制转换为FilePollerConfiguration

3 个答案:

答案 0 :(得分:1)

仅当LoadFilePollerConfiguration延长FilePollerConfiguration时,

LoadFilePollerConfiguration才能投放到FilePollerConfiguration

从您的问题来看,您似乎误解了Interface的概念。进一步解释下面的代码。

Inteface iSample {
  void doThing();
  //more code
}

class Parent implements iSample {
  void doThing() {
     System.out.println("Parent");
  }
}

class AnotherParent implements iSample {
  void doThing() {
     System.out.println("Another Parent");
  }
}

class Child extends Parent implements iSample{
   //child specific code
}

class Test {
   public static void main(String[] args) {
       iSample i = new Parent();
       iSample j = new AnotherParent();
       iSample k = new Child();
       Parent p = j; //error
   }
}

仅仅因为ParentAnotherParent实现了iSample,这并不意味着Parent对象可以容纳AnotherParent的对象。但是接口iSample的引用可以包含ParentAnotherParent两个实现iSample,它也可以包含Child的实例,因为它的超类已完成界面合同

答案 1 :(得分:0)

我认为您的问题在WatchSer构造函数中退出

public class WatchSer {    

    private final WatchService watcher;     
    private final Map<WatchKey,Path> keys;          
    private boolean trace = false;  
    private FilePollerConfiguration configuration;

    WatchSer(IConfig conf) throws IOException {    

        this.watcher = FileSystems.getDefault().newWatchService();         
        this.keys = new HashMap<WatchKey,Path>();   
        configuration = (**FilePollerConfiguration**) conf;

    }

其中'FilePollerConfiguration'应为'LoadFilePollerConfiguration'

答案 2 :(得分:0)

我找到了解决方案,我删除了我的loadFilePollerConfiguration类,并修改了我的主要内容:

public class Main {

    private IConfig loadConfig(File configFile) throws Exception{
        SchemaFactory sf = SchemaFactory.newInstance
                      (XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(new File("config.xsd"));
        JAXBContext jc = JAXBContext.newInstance
                      (FilePollerConfiguration.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        unmarshaller.setSchema(schema);
        unmarshaller.setEventHandler(new MyValidationEventHandler());
        FilePollerConfiguration f = (FilePollerConfiguration)  unmarshaller
                      .unmarshal(configFile);

        Marshaller mar = jc.createMarshaller();
        mar.marshal(f, new File("test.xml"));

        return f;
    }

    /**
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception{
        // TODO Auto-generated method stub
        IConfig conf = new Main().loadConfig(
                       new File("P://Projects//FileTransfer//config.xml"));
        WatchSer w = new WatchSer(conf);
        w.getAction(new File("C://Users//jmoreau040612//
                       Desktop//Old"), "create");
        //w.processEvents();
    }

}