Bonsoir à tous,
j'ai un petit soucis au niveau de mon code.
Soucieux de séparer le traitement des données, j'ai créé une énumération comme suit:
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| public enum CatalogEnum {
SupplierName (String.class, "getFournisseur"),
;
private Class defaultValueType;
private Object accessMethod;
CatalogEnum (Class defaultValueType, Object accessMethod) {
this.defaultValueType = defaultValueType;
this.defaultValueOrAccessMethod = accessMethod;
}
public Object accessMethod() {
return accessMethod;
}
public Class defaultValueType () {
return defaultValueType;
}
public Object getValue (Catalog catalog) {
return defaultValueType.cast(getCatalogDomainValueByDynamicCall (catalog));
}
public Object getCatalogDomainValueByDynamicCall (Catalog catalog) {
Class clazz = catalog.getClass();
Method method = null;
try {
method = clazz.getMethod((String) accessMethod, Class[].class.cast(null));
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
try {
return method.invoke(catalog, Object[].class.cast(null));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
} |
Elle m'indique le nom de la méthode à appeler dynamiquement est "getFournisseur" et le type retourné par "getFournisseur" est "String.class".
Lorsque j'appelle mon énumération:
flux.setFournisseur(CatalogEnum.SupplierName.getValue(catalogLine));
Eclipse me mets l'erreur suivante:
The method setFournisseur(String) in the type FluxBase.Flux is not applicable
for the arguments (Object)
Il faudrait que j'arrive à renvoyer explicitement le bon type, tout en évitant de préfixer mon appel comme suit:
(String) CatalogEnum.SupplierName.getValue(catalogLine)
J'ai regardé du côté des annotations pour indiquer à la compil de ne pas se soucier des types mais je n'ai rien trouvé. Ou alors mieux utiliser les énumérations...
Merci pour vos suggestions.
Partager