swa*_*nee 6 java generics casting unchecked-cast
我有以下测试代码:
FileSystem fs = FileSystems.getDefault();
Path conf = fs.getPath(".");
WatchKey key = null;
try {
WatchService watcher = fs.newWatchService();
conf.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
while(true) {
key = watcher.take(); // waits
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (StandardWatchEventKinds.OVERFLOW == kind) continue;
WatchEvent<Path> ev = (WatchEvent<Path>)event;
Path file = ev.context();
System.out.println(file);
}
}
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e.getMessage(), e);
}
Run Code Online (Sandbox Code Playgroud)
编译器unchecked cast
发出与该行相关的警告
WatchEvent<Path> ev = (WatchEvent<Path>)event;
Run Code Online (Sandbox Code Playgroud)
因为作为一个event
出来,编译器无法判断在运行时它是否真的要包含一个,而不是其他东西.key.pollEvents()
WatchEvent<?>
Path
对此,我想知道是否有可能在没有明确压制它的情况下摆脱这个警告.我找到了一些提示,虽然与完全不同的情况有关,就像这样,但在这里似乎他们可以控制通用列表的构建方式,而在我的情况下,这是不可能的.
我也发现了这一点,他们建议抑制警告,同时检查实际类型是否正确(因为编译器不能单独执行),但我无法做到在我的情况下这些线.可能吗?你会怎么做?
另一方面,在我的情况下,我WatchEvent
从一个对象的WatchService
注册中得到这些Path
:这个事实是否足以证明每WatchEvent<?>
一个从这里出来WatchService<?>
都会有Path
类型实现?如果这是真的,我可以安全地假设演员阵容总是正确并且禁止警告吗?在这种情况下,有没有办法避免它而没有压制它?
非常感谢你.
我可以立即检查明确说明的引用:
T context()
返回事件的上下文.
对于ENTRY_CREATE,ENTRY_DELETE和ENTRY_MODIFY事件,上下文是Path,它是向watch服务注册的目录与创建,删除或修改的条目之间的相对路径.
所以在我的情况下,我正在观看ENTRY_MODIFY
事件,因此我的T
类型是定义的Path
.
我认为最好的选择就是压制它
@SuppressWarnings("unchecked")
WatchEvent<Path> ev = (WatchEvent<Path>)event;
Run Code Online (Sandbox Code Playgroud)
它是绝对安全的,只能是安全,<Path>
仅此而已。API 设计者因为太笼统而有点疯狂。
WatchService
有点难用。我有以下您可能感兴趣的实用程序类
https://github.com/zhong-j-yu/bayou/blob/0.9/src/_bayou/_tmp/_FileMonitor.java
例如
_FileMonitor monitor = new _FileMonitor( ROOT_DIR );
List<Set<Path>> changes = monitor.pollFileChanges( TIMEOUT )
// return 3 sets, [0]=created, [1]=modified, [2]=deleted
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
733 次 |
最近记录: |