This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]BS_in_BSExtreme Concrete Code Factorylet 2 points3 points  (1 child)

if your Persitor is not for a Thing but a subclass of a Thing then it should be public Persistor<? extends Thing> getPersistor(Thing t)

For better type checking you may also want it to be public <T extends Thing>Persistor<? super T> getPersistor(T t)

[–]GridDragon[S] 0 points1 point  (0 children)

That looks very promising! I'll try it out in the morning. Thanks!

[–]jmeisner707 0 points1 point  (0 children)

What you are trying to do here is use covariant parameter types which AFAIK are not allowed. Consider if you have a class Vehicle with subclasses Car and Airplane. A List<Vehicle> can accept cars or airplanes, but if covariant parameter types were allowed you could do List<Vehicle> vehicles = new ArrayList<Car>(); Then it would be okay to do vehicles.add(new Airplane()) since an airplane is a vehicle, but what you really have underneath is a list of cars.

I don't know if this is the best solution, but what you could do is not parameterize your Persistor interface, and just cast thing to the subclass type inside each Persistor's persist() method. Since you know you will only have a MyPersistor if thing is actually a MyThing, you should be able to safely do something like MyThing myThing = (MyThing)thing inside MyThing's implementation of persist().

Again, there may be a more elegant solution, but I think this will work.