避免if else声明

时间:2015-06-24 22:10:04

标签: java if-statement

我有50个不同的课程。我用这50个课程制作了一个通用类(全部)。

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());
       }
...

我不喜欢这种配置,因为对于这么多类来说,它是一个不可读的代码。

如何改进此代码?

3 个答案:

答案 0 :(得分:2)

以下代码可能对您有所帮助:

 All all = new All();

 String result;

 for(int i = 0; i++ < all.length(); ) {
     YourInterface element = all.get(i);
     if(element != null)
         result = method(element);
 }

其中,

  • length() - 课程数量
  • get(int index) - 访问方法 来自索引的元素
  • YourInterface - 您所有人的通用界面 类

下一步是使用反射。

答案 1 :(得分:1)

你绝对可以使用Reflection或创建自己的版本来清理它。 你有类似的东西:all.getObjects();然后对2维数组进行反弹以获取调用所需的方法然后调用它。

如果我稍后再回来完成此操作。但在那之前我发现了一些事情:

using reflection to get objects from collection class

What is reflection and why is it useful?

答案 2 :(得分:1)

operator()
相关问题