java - In a Transformer, how to specify that the types fo the classes being transformed are of the same type? -
i'm having simple yet confuse question @ same time.
in transformer, there way specify types of classes beingness transformed same type?
to create clear, i'll share code:
transformer<set<?>, list<?>> transformer = new settolisttransformer();
is there way me specify set , list of same type?
also when writing transformer did this, , assume serves no purpose:
private static class settolisttransformer implements transformer<set<?>, list<?>> { @override public list<?> transform(final set<?> input) { homecoming this.dotransform(input); } public <t> list<t> dotransform(final set<t> input) { ... } }
the thing is, cannot type settolisttransformer since not care types inside, care same type.
any help appreciated!
ps: i'm not transforming set list, i'm using other types, used them clarify code :)
there's no way enforce desired constraint on transform
implementation, since there no way impose relationship between generic wildcards. each of 2 ?
in settolisttransformer
declaration doomed each mean some unknown type no way bound them each other.
as others pointed out, easiest solution create settolisttransformer
generic. example:
class settolisttransformer<t> implements transformer<set<? extends t>, list<t>> { @override public list<t> transform(final set<? extends t> input) { final list<t> output = new arraylist<t>(input.size()); output.addall(input); homecoming output; } }
of course of study requires instantiate transformers specific type arguments. should fine long settolisttransformer
cheap. but, indicated want utilize 1 instance. here's how that:
class mytransformers { // there no reason expose settolisttransformer now. // maintain here anonymous class. private static final transformer<set<?>, list<?>> from_set_to_list = new transformer<set<?>, list<?>>() { @override public list<?> transform(final set<?> input) { homecoming dotransform(input); } private <t> list<t> dotransform(final set<t> input) { final list<t> output = new arraylist<t>(input.size()); output.addall(input); homecoming output; } }; private mytransformers() { } public static <t> transformer<set<? extends t>, list<t>> fromsettolist() { @suppresswarnings("unchecked")//this okay t because impl stateless final transformer<set<? extends t>, list<t>> withnarrowedtypes = (transformer<set<? extends t>, list<t>>)(transformer<?, ?>)from_set_to_list; homecoming withnarrowedtypes; } }
here's usage example:
set<integer> intset = new hashset<integer>(); intset.add(42); intset.add(1337); list<number> numlist = mytransformers.<number>fromsettolist().transform(intset);
java generics
No comments:
Post a Comment