java - Making assumptions about type parameters? -
i want subclass iterator i'll call fooiterator. code looks this:
public class fooiterator<e> implements iterator<e> { public fooiterator(collection<bar> bars) { inneriterator = bars.iterator(); } @override public boolean hasnext() { return inneriterator.hasnext(); } @suppresswarnings("unchecked") @override public e next() { bar bar = inneriterator.next(); return new e(bar); } @override public void remove() { throw new unsupportedoperationexception("don't remove fooiterator!"); } private iterator<bar> inneriterator; }
...except, of course, doesn't work because can't instantiate new e bar.
i ever use e has constructor takes bar. there way "prove" compiler, or throw runtime error if e doesn't have appropriate constructor?
or perhaps i'm not using right design pattern here? i've been doing lot of c++ recently, , feel might approaching wrong way.
this convoluted approach work , type safe (solutions using reflection won't). consists in delegating construction of e
bar
separate class. have barconverter
interface:
interface barconverter<e> { e convert (bar bar); }
then class become:
public class fooiterator<e> implements iterator<e> { public fooiterator(collection<bar> bars, barconverter<e> converter) { inneriterator = bars.iterator(); this.converter = converter; } @override public e next() { bar bar = inneriterator.next(); return converter(bar); } }
Comments
Post a Comment