generics - Java - Is it safe to suppress unchecked cast warning with WatchEvent? -


i have following test code:

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         (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); } 

the compiler issues unchecked cast warning related line

watchevent<path> ev = (watchevent<path>)event; 

since event comes out of key.pollevents() watchevent<?>, , compiler can't tell if during runtime it's going contain path, , not else.

regarding this, wondering if it's possible rid of warning without explicitly suppressing it. found hint, although related quite different situations, this, here seems can control how generic list built, while in case isn't possible.

i found this, suggest suppress warning, checking @ same time if actual type correct 1 (since compiler can't on own), couldn't manage along these lines in case. possible? how it?

on other hand, in case i'm getting these watchevent's watchservice registered path object: fact alone enough prove every watchevent<?> coming out watchservice<?> have path type implementation? if true, can safely assume cast correct , suppress warning? there way avoid without suppressing in case?

thank much.

edit

i have checked the references explicitly state that:

t context()

returns context event.

in case of entry_create, entry_delete, , entry_modify events context path relative path between directory registered watch service, , entry created, deleted, or modified.

so in case i'm watching entry_modify events, hence t type definetely path.

i think best option suppress it

            @suppresswarnings("unchecked")             watchevent<path> ev = (watchevent<path>)event; 

it's safe, can <path> , nothing else. api designer went little crazy of being general.

watchservice kind of difficult use. have following utility class might intereted in

https://github.com/zhong-j-yu/bayou/blob/0.9/src/_bayou/_tmp/_filemonitor.java

for example

_filemonitor monitor = new _filemonitor( root_dir );  list<set<path>> changes = monitor.pollfilechanges( timeout ) // return 3 sets, [0]=created, [1]=modified, [2]=deleted 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -