我在使用 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 时,我遇到了一个演员问题:
>
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");
}
}
线程“主”java.lang.ClassCastException 中的异常:LoadFilePollerConfiguration 无法转换为 FilePollerConfiguration