【问题标题】:How to add methods in dynamic string and call them according to for loop condition?如何在动态字符串中添加方法并根据for循环条件调用它们?
【发布时间】:2019-01-03 23:33:55
【问题描述】:

我想根据for循环条件在一个字符串中调用多个方法。

这段代码应该可以帮助你理解我在寻找什么:

public void onItemClick(View view, int position) {
    for (count=0;count<=25;count++){
        if (count==position){
            String methodCall="A"+count+"List()";
            A0List()=methodCall;
        }
    }
}

A0List(){
     //Body 
     //when count=0 this method is called
}

A1List(){
    //body
    //when count=1 this method is called
}

// ...

A25List(){
   //body
   //when count=25 this method is called
}

我在我的 Android 应用上使用此代码来减少点击侦听器代码。

我正在寻找一种避免 if-else-if 阶梯循环的解决方案。

【问题讨论】:

  • 您可以使用反射来实现,但我不会推荐它。相反,我相信您的 AXList() 方法中的代码会非常相似,因此您应该只有一个方法并将数字作为参数传递。你能用其中几种方法显示代码来确认这一点吗?
  • 使用适配器将值放入另一个类或 Andorid 活动中

标签: java string android-studio for-loop methods


【解决方案1】:

您要问的内容在这里: How do I invoke a Java method when given the method name as a string?

但在大多数情况下,比反射更可取的是显式映射。这样,您的函数名称就不必按名称绑定到某个位置。映射必须在某处完成。我看不出方法名称是如何适合的:

Map<Integer, Runnable> functionMap = new HashMap<>();
functionMap.put(0, () -> A0List());
functionMap.put(1, () -> {/*A1List body*/});
// etc
functionMap.put(25, () -> someMeaningfulMethodName());

那么你的功能是:

public void onItemClick(View view, int position) {
    functionMap.getOrDefault(position, () -> {/* handle incorrect position */}).run();
}

更简单的是 switch 语句:

switch(position)
{
    case 0: A0List(); break;
    case 1: A1List(); break;
    // etc
    case 25: A25List(); break;
    default: /* handle unknown position */ break;
}

【讨论】:

  • 谢谢。但是 switch 和 map 它与 if-else-if 梯形循环相同。我想要更多的利用
  • 映射必须在某处完成。我不认为在方法名称中这样做是一个好主意,但如果你必须这样做,这将有助于stackoverflow.com/questions/160970/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多