Factorisation de méthodes : généricité / polymorphisme
Bonjour !
Voilà je souhaite créer une fonction statique générique, mais je n'y parviens pas. Pour mieux expliquer mon point bloquant, je vous met un code relativement court ci dessous.
PS : En réalité, ce code ne correspond à rien, mais reprend la structure de mon vrai code, ce dernier étant autrement plus long et plus complexe (60 000 lignes héhé ^^). Ainsi si certains éléments ne vous semble pas logique, ne vous en offusquez pas.
Voici mes deux classes statiques que je souhaite factoriser :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public class Tools {
private static int getValuePersonne(String attributNom) {
java.lang.Object objet;
Personne cible = (Personne)objet;
return cible.getAttribut(attributNom);
}
private static int getValueEntreprise(String attributNom) {
java.lang.Object objet;
Entreprise cible = (Entreprise)objet;
return cible.getAttribut(attributNom);
}
} |
Pour info voici les deux types de classes dont il est question plus haut :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| public class Personne {
private int age;
private int taille;
public int getAge() {
return age;
}
public int getTaille() {
return taille;
}
/**
* Getter générique
* @param attributNom
* @return
*/
public Object getAttribut(String attributNom) {
if(attributNom.equals("age")) {
return this.getAge();
}
else if(data.equals("taille")) {
return this.getTaille();
}
return null;
}
} |
et
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| public class Entreprise {
private int nombreEmployes;
private int salaireMoyen;
public int getNombreEmployes() {
return nombreEmployes;
}
public int getSalaireMoyen() {
return salaireMoyen;
}
/**
* Getter générique
* @param attributNom
* @return
*/
public Object getAttribut(String attributNom) {
if(attributNom.equals("nombreEmployes")) {
return this.getNombreEmployes();
}
else if(attributNom.equals("salaireMoyen")) {
return this.getSalaireMoyen();
}
return null;
}
} |
Un grand merci à tous ceux qui voudront bien y jeter un oeil. Je continue d'investiguer de mon côté et de tenir à jour ce post.
EDIT : correction erreurs de code.