gpt4 book ai didi

java - 为不同的类执行相同的功能

转载 作者:行者123 更新时间:2023-12-02 13:28:13 24 4
gpt4 key购买 nike

我正在制作一些在处理中处理 JSON 的东西。输入格式很灵活,因此我经常需要为不同的类执行相同的代码。除了我所做的之外,还有其他首选方法吗?

Object part = json.get(0);
File saveTo = new File(dataPath("test.txt"));
if (part.getClass() == JSONObject.class)
((JSONObject)part).save(saveTo, "");
if (part.getClass() == JSONArray.class)
((JSONArray)part).save(saveTo, "");

最佳答案

几件事:

首先,您应该始终将 if 包裹起来。 { } 中的语句大括号。

Object part = json.get(0);
File saveTo = new File(dataPath("test.txt"));
if (part.getClass() == JSONObject.class){
((JSONObject)part).save(saveTo, "");
}
if (part.getClass() == JSONArray.class){
((JSONArray)part).save(saveTo, "");
}

其次,如果您只期望其中之一 if要执行的语句,那么您可能应该使用 else if :

Object part = json.get(0);
File saveTo = new File(dataPath("test.txt"));
if (part.getClass() == JSONObject.class){
((JSONObject)part).save(saveTo, "");
}
else if (part.getClass() == JSONArray.class){
((JSONArray)part).save(saveTo, "");
}

第三,您可以使用 instanceof运算符而不是获取类:

Object part = json.get(0);
File saveTo = new File(dataPath("test.txt"));
if (part instanceof JSONObject){
((JSONObject)part).save(saveTo, "");
}
else if (part instanceof JSONArray){
((JSONArray)part).save(saveTo, "");
}

但是要回答你的问题,没有一个很好的方法来最小化此代码,因为 JSONObjectJSONArray都是 Object 的直接子类。如果 JSONArray 会更容易是 JSONObject 的子类,但事实并非如此。

但是,如果您发现自己在多个位置编写此代码,则应该将其提取到一个函数中,如下所示:

void saveJsonThing(Object part, File file)
if (part instanceof JSONObject){
((JSONObject)part).save(saveTo, "");
}
else if (part instanceof JSONArray){
((JSONArray)part).save(saveTo, "");
}
else{
//handle error?
}
}

然后您的代码可以在需要保存某些内容时调用该函数:

Object part = json.get(0);
File saveTo = new File(dataPath("test.txt"));
saveJsonThing(part, saveTo);

关于java - 为不同的类执行相同的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43305871/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com