[Update]: my initial example doesn't reflect my problem. Updated the sample, hopfully it is better now.
Java Generic and overloading don't play well together.
public interface Request<E> {
E getValue();
}
I have a generic parameterized Request interface as above, and I would like write a DataStore class to save the payload request carries. The save logic is different for different payload type.
What I really want is something like
public interface DataStore {
void save(Request<E1> r);
void save(Request<E2> r);
}
But this is of course illegal.
If I want to preserve type safety, DataStore must declare different methods for each type I want to handle, e.g
public interface DataStore {
// here E1 is the actual type I want to handle, not a generic parameter
public void saveE1(Request<E1> e);
public void saveE2(Request<E2> e);
}
Or sacrifices type safety
public class DataStore {
public void save(Request e) {
Object value = e.getValue();
if (value instanceof ReqE1Impl) {
// do something
} else if (value instanceof ReqE2Impl) {
// do something else
}
}
}
Both ways suck! Is there any better way?