Java Generic Question: A better way?

advertisements

[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?


The better way to do this would involve the object knowing how to save itself. If you still want to use a DataStore, you could do something like this:

interface YourInterface {
  void save();
}

interface Request<E extends YourInterface> {
  E getValue();
} 

class DataStore<E extends YourInterface> {
  public void save(Request<E> r) {
    r.getValue().save();
  }
}

You just have to ensure that your objects then each implement that interface and viola, you have Generics and polymorphism playing nice with each other.

NOTE: The way your (revised) question is written, you are not using polymorphism. You are using overloading. Method overloading is decided at compile time, while method polymorphism is decided at runtime. This is part of why you are running into these difficulties.

If you really do not want the above kind of design where the objects do all the work of saving themselves, then perhaps you can do something like this (as a very weak example):

interface YourInterface {
  String serialize();
}

interface Request<E extends YourInterface> {
  E getValue();
} 

class DataStore<E extends YourInterface> {
  public void save(Request<E> r) {
    String value = r.getValue().serialize();
    // Now do something with value to save to a datastore
  }
}

Above is a weak example, but the main idea is that the objects know how to do the part of serialization that differs between objects, and the DataStore can then do the work that is common to all of your objects.

And yes, you are right (with the wrong terminology) -- generics don't play nice with overloading. But they do play nice with polymorphism. Polymorphism is usually a better instrument than overloading anyway.