I have a parent, lets call it Bike that has a name and a color.
public class Bike(){
String name;
String color;
}
I have 2 children
public class TrickBike extends Bike(){
...
...
public doTrick(){
}
}
public class FailBike extends Bike(){
...
...
public doFail(){
}
}
These all have appropriate construtor super calls and everything. I now have a garage that holds bikes.
public class Garage(){
List<Bike> bikes;
}
I add a bunch of bikes, all 3 types(Bike, TrickBike,FailBike
). Now, I write this to a JSON String and dump to file with GSON. I then at a later time get the Garage from the JSON file with GSON and I want to try to doTrick()
on a TrickBike
. I can't cast Bike
to TrickBike
now because of the Json conversion (this is from trial and error and getting exception in java). So how do I restore this child functionality?
Is there a safe way of doing this? An unsafe way? If I try doTrick()
on a FailBike
what happens? Can I get the Bike
to try and doTrick()
?
Thanks.
EDIT: I would like to fix this post-GSON read in. @Chaosfire mentioned copying some GSON source code from the linked question but I would not like to do this for a variety of reasons. Also, I am not reading types TrickBike
and Bike
or FailBike
in. I am reading in the Garage
which merely has a List<Bike>
so that wouldn't work.
SOLUTION: I migrated over to using jackson and was able to successfully implement this behavior using annotations and @JsonTypeInfo with type labels. So Jackson > Gson for polymorphism.