Java 避免if-else语句
我有50门不同的课。我用这50个类创建了一个泛型类(All)Java 避免if-else语句,java,if-statement,Java,If Statement,我有50门不同的课。我用这50个类创建了一个泛型类(All) public class All { private First first; private Second second; private Third third; ... //GETTERS AND SETTERS } 我有一个通用方法,其中有一段代码: All all=new All(); String result; if(all.getFirst()!=null
public class All {
private First first;
private Second second;
private Third third;
...
//GETTERS AND SETTERS
}
我有一个通用方法,其中有一段代码:
All all=new All();
String result;
if(all.getFirst()!=null){
result=methodA(all.getFirst());
}
else if(all.getSecond()!=null){
result=methodB(all.getSecond());
}
else if(all.getThird()!=null){
result=methodC(all.getThird());
}
...
我不喜欢这种配置,因为对于这么多的类来说,它是一个不可读的代码
如何改进此代码?您可以通过反射或创建自己的版本来清除此代码。 您将得到如下内容:all.getObjects();然后让该反弹在二维数组上,以获取调用所需的方法,然后调用该方法 如果我晚些时候再来完成这件事。但在此之前,我发现了一些东西:
以下代码可能对您有所帮助:
All all = new All();
String result;
for(int i = 0; i++ < all.length(); ) {
YourInterface element = all.get(i);
if(element != null)
result = method(element);
}
All=newall();
字符串结果;
对于(int i=0;i++
在哪里,
-类的数量length()
-访问方法 索引中的元素get(int-index)
-适用于所有用户的通用界面 班级YourInterface
下一步是使用反射。反射可能会帮助您…查找策略和工厂方法模式。您需要在循环中为执行
get(int index)
,运行所有元素并检查为null
String result = all.getFirst() != null ? methodA(all.getFirst())
: all.getSecond() != null ? methodB(all.getSecond())
: all.getThird() != null ? methodC(all.getThird())
: null;