Generics - re-writed version
Hello all. I am building a small app that requires a persistence manager to save objects in an xml repository file.
I am trying to use generics to see if I can avoid casting objects from a general super class to concrete class. Lets say Entity and Person.
For a store method. I wrote this:
public <Eextends Entity>void store(E entity);
Lets say that inside store method I delegate the translation from the entity Person or whatever to a Node element. Somewhere you would have to cast the E type (from generics) to Person. right? like:
persistence manager code:
privatevoid save(Person person){
..transform the object to xml and save it
}
public <Eextends Entity>void store(E entity){
this.save((Person)entity);
}
client code:
Person person =new Person("Jon","Stewart");
myStorage.store(person);
May be the GET statement would be easier to understand. My get looks something like this:
persistence manager code:
public <Eextends Entity> E getEntity(int id){
returnnull;
}
client side code:
Person person = myStorage.get(32);
I avoid casting from the client side by using generics here.
How can I best avoid casting?
You see, I am trying to avoid Casting as much as I can.
I have to translate an entity to an xml node, then append the node to a parent node, thus persisting it to the original document.
I created some XmlTranslators. and a subclass for each different type of entity. I don't think this is such a good aproach. But I didn't had any better Idea at the time (would be great to hear sugestions).
I have a Switch statement that evaluates the entity.entityType (an enumerator type) and as I showed before in the example I cast to the subclass type (Person).
Am I doing this the right way? or just the complicated way.
My goal is to reduce code in store methods and avoid as much casting as I can.
May be by trying to do it all I got a little lost. If some one could share his/her views on the matter and maybe show me a better practice, I would appreciate it very much.

