I have made inteface switch, maybe it can be useful for someone :
new ISwitch(pagerCtrl.getPager().getFragmentByID(fragment_id))
.addCase(new ISwitch.CaseListener<Type1>() {
@Override
public void Case(Type1 instance) {
}
}).addCase(new ISwitch.CaseListener<Type2>() {
@Override
public void Case(Type2 instance) {
}
}).addDefault(new ISwitch.DefaultListener() {
@Override
public void Default() {
}
}).build();
public class ISwitch {
public interface CaseListener<T> {
void Case(T instance);
}
public interface DefaultListener {
void Default();
}
Object value;
LinkedList<CaseListener<?>> col = new LinkedList<>();
DefaultListener defaultListener;
public ISwitch(Object value) {
this.value = value;
}
public void build() {
boolean wasNotifiedMinimumOnce = false;
for (CaseListener<?> c : col) {
try {
CaseListener<Object> l = (CaseListener<Object>) c;
l.Case(value);
wasNotifiedMinimumOnce = true;
break;
} catch (ClassCastException e) {
}
}
if ( !wasNotifiedMinimumOnce ) {
if ( defaultListener != null ) {
defaultListener.Default();
}
}
}
public ISwitch addCase(CaseListener<?> caseListener) {
col.add(caseListener);
return this;
}
public ISwitch addDefault(DefaultListener defaultListener) {
this.defaultListener = defaultListener;
return this;
}
}
The small drawback of implementation is that we cant make check instanceof, that why i catch it on cast. For me its not big deal, but it can be performance issue on java server code executed XXXXXX times each seconds.