场景: 根据不同条件值取不同的字段值
例如 :
Score score= new Score();
switch (itemDetail.getEvaluationCode()) {
case 1:
score.getCostLevel()
break;
case 2:
score.getScarcityLevel()
break;
case 3:
// 计算数据完整性对应的系数
score.getIntegrityLevel()
break;
}
使用反射的写法如下:
private static String getFieldValue(Score score,String youField ) throws NoSuchFieldException, IllegalAccessException {
Class<? extends Score> clazz1 = score.getClass();
Field field = clazz1.getDeclaredField(youField);//获取私有字段
field.setAccessible(true);//设置权限
return (String) field.get(score);
}
在加一个枚举
COST("COST","cost"),
private String key;
private String value;
private YouClassName(String key,String value){
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}
public static String getValueByCode(String code){
for (YouClassNameele : values()) {
if(ele.getKey().equals(code)) return ele.getValue();
}
return null;
}