lundi 4 décembre 2017

Understanding Generics and Reflection in Java to Make Array Generic

I am trying to model a train with a Java program. Currently I have four classes : Train Class, BoxCar Class, Cargo Class, and Person Class. The BoxCar class has an array of type Person and an array of type Cargo. A BoxCar can only hold one type so when that type is given from the constructor, I decide which array to use (either the people array or the cargo array). The thing is, I'd like to make that array inside BoxCar "generic" so that if there is another "kind" of type the user wants to use, it can be easily set-- they wouldn't need to declare another array inside the BoxCar class for that type and change the rest of the code. How would I do this? I looked up Generic and Reflection but the examples I saw weren't exactly for my scenario and I'm learning this for the first time. Can someone map out the right approach to take? Thank you





Aucun commentaire:

Enregistrer un commentaire