简体   繁体   English

如何为多个if-else语句编写函数

[英]how to write function for multiple if-else statements

I am new to Java. 我是Java新手。 I have lots of multiple if-else statements. 我有很多多个if-else语句。 For code optimization purpose I need to write one function for all if else logic. 出于代码优化的目的,我需要为所有其他逻辑编写一个函数。

if (obj.getJSONObject("page_1").has("city")) {
    sn.city = (String) obj.getJSONObject("page_1").get("city").toString();
} else {
    sn.city = null;
}

// param 2 - locality

if (obj.getJSONObject("page_1").has("locality")) {
    locality = (String) obj.getJSONObject("page_1").get("locality").toString();
} else {
    locality = null;
}

I have like 110 if -else statements. 我喜欢110 if -else语句。 I don't have any idea how to optimize the code. 我不知道如何优化代码。

I might write a function something like: 我可能会写一个类似以下的函数:

static String getToStringOrNull(JSONObject parent, String key) {
  return parent.has(key) ? parent.get(key).toString() : null;
}

which you can then call like 然后你可以打电话给

sn.city = getToStringOrNull(obj.getJSONObject("page_1"), "city");
locality = getToStringOrNull(obj.getJSONObject("page_1"), "locality");

I think the best use would be this notation ( ternary operator ): 我认为最好的用法是这种表示法( 三元运算符 ):

sn.city = (obj.getJSONObject("page_1").has("city")) ? 
                    (String) obj.getJSONObject("page_1").get("city").toString() : null;

The part before ? 之前的部分? stands for the if-statement, the second part if the condition was fulfilled and the last part otherwise. 代表if陈述,如果条件满足,则代表第二部分,否则则代表最后一部分。

For all direct fields of your class, you may use reflection (and you could do the same work on the sn object if you want ) : 对于类的所有直接字段,您可以使用反射(如果需要,可以对sn对象执行相同的工作):

Class aClass = this.getClass();

Field[] fields = aClass.getFields();

for (Field field : fields) {


   String value = (obj.getJSONObject("page_1").has(field.getName())) ?
            (String) obj.getJSONObject("page_1").get(field.getName()).toString() : null;

   field.set(this, value);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM