dynamic binding with generic type

2.4k views Asked by At

i need to bind dynamic a parametic type (List) but i dont get it right... here is an overview of my classes:

public abstract interface SettingsField<A> extends Window

then i have some classes which implements SettingsField:

public class StringSettingsField implements SettingsField<String>
public class MapSettingsField<K, V> implements SettingsField<Map<K, V>>

the first is real simple, but eg the second is a little bit tricky... so i want to make a factory which returns SettingsFileds. I want to use dynamic binding to get the right SettingsWindow for each Object i want to put in there. so i overload a method getField the following. for String its quite easy:

public SettingsField<String> getField(String x){
    return new StringSettingsField();
}

but for map i have some trouble...

public SettingsField<Map<? extends String, ?>> getField(Map<? extends String, ?> x){
    return new MapSettingsField();
}

that the key is always a string is an exampe (could be ? also) but now the compiler gives me the waring that

MapSettingsField is a raw type. References to generic type MapSettingsField should be parameterized

but how i can do this here? the problem is just use Map is not valid, because of some problem with f-generic in java (List is not implicit subtype of List even if B is subtype of A)

any hints? thanks in advance!

1

There are 1 answers

2
maaartinus On BEST ANSWER

IIUYC, you need

return new MapSettingsField<? extends String, ?>();

Btw., extends String doesn't make much sense as String is final.

However, I'd go for something like

public <K, V> SettingsField<Map<K, V>> getField(Map<K, V> x){
    return new MapSettingsField<K, V>();
}

You could declare K as bounded, too, e.g.

public <K extends Number, V extends List> ...

or whatever.