对于异常处理,我想知道,给定Bean中的哪个getter / field产生了Exception。我不希望在每个getter调用周围进行尝试/捕获,或者必须手动跟踪String变量。
我可以使用Java Reflections吗?如何设计Bean实现的接口?
我希望发生异常处理的伪代码:
try {
step.setNo(Long.parseLong(stepElement.getChildText("no", nameSpace)));
step.setName(stepElement.getChildText("name", nameSpace));
step.setDetail(stepElement.getChildText("detail", nameSpace));
step.setEcuName(stepElement.getChildText("ecu-name", nameSpace));
}catch(Exception e){
String fieldname = /*which field did throw? */
}
部分实际Bean:
public class CupProcStep {
private long no;
private String name;
private String detail;
private String ecuName;
private String ecuVariant;
private String diagnosticsId;
private String errorText;
private String stepResult;
public long getNo() {
return no;
}
public void setNo(long no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public String getEcuName() {
return ecuName;
}
引发异常的字段名称,例如“否”,“名称”,“ ecuName”等。
反射几乎总是错误的解决方案。
在执行可能抛出的代码期间存储相关字段名称非常容易。
String fieldName = "no";
try {
step.setNo(Long.parseLong(stepElement.getChildText("no", nameSpace)));
fieldName = "name";
step.setName(stepElement.getChildText("name", nameSpace));
fieldName = "detail";
step.setDetail(stepElement.getChildText("detail", nameSpace));
fieldName = "ecu-name";
step.setEcuName(stepElement.getChildText("ecu-name", nameSpace));
} catch (Exception exc) { // Be more specific!
// fieldName available here
}
在这种情况下,我们只需编写一次字段名称就可以更好地确保我们不会出现复制粘贴错误。
String fieldName = "no";
try {
step.setNo(Long.parseLong(stepElement.getChildText(fieldName, nameSpace)));
fieldName = "name";
step.setName(stepElement.getChildText(fieldName, nameSpace));
fieldName = "detail";
step.setDetail(stepElement.getChildText(fieldName, nameSpace));
fieldName = "ecu-name";
step.setEcuName(stepElement.getChildText(fieldName, nameSpace));
} catch (Exception exc) { // Be more specific!
// fieldName available here
}
有些人会将赋值放在方法调用(getChildText(fieldName = "ecu-name",
)中,但我不喜欢子表达式中的副作用。
整个stepElement.getChildText(fieldName, nameSpace)
是重复的代码,对于其他类型也可能重复。将此作为一个类来进行练习。 try-catch
部分可以使用Execute Around惯用法来分解。