java - using generics correctly with maps -
i have sorts of items extending baseitem. each type have special handler class.
i use map of handlers, using item classname. handling method this:
private boolean handle(baseitem item) { baseitemhandler bih = mapofhandlers.get(item.getclass().getsimplename()); return bih.handleitem(item); }
and map of type:
map<string,baseitemhandler> mapofhandlers;
but i'm (obviously) getting "unchecked call" warning. correct way of doing
edit:
items
public interface baseitem{}
and baseitemhandler is:
public interface baseitemhandler<t extends baseitem> { public boolean handleitem(t item); }
java.util.map not permit expressing type constraint between individual key , value, , if did, generics weak make use of constraint in map.get(), implementation of map.get() can not convince compiler type parameter of argument identical type parameter of map entry being accessed. such implementation therefore require cast.
you can use checked cast, though:
abstract class handler<i extends baseitem> { final class<i> iclass; protected handler(class<i> iclass) { this.iclass = iclass; } void handle(baseitem i) { dohandle(iclass.cast(i)); } abstract void dohandle(i i); }
however, introduces method overly permissive signature, , callers might accidentally use signature elsewhere in program, needlessly bypassing compile time type checking. unchecked cast seems lesser price pay.
if concerned possiblity of heap pollution, i'd check type of handler during registration:
class handlermap { map<class<?>, handler<?>> map = new hashmap<>(); public void register(handler<?> h) { map.put(h.iclass, h); } public <i extends baseitem> handler<i> get(i i) { return (handler<i>) map.get(i.getclass()); } }
Comments
Post a Comment