【问题标题】:Is it possible to do getMethodX with a for? [duplicate]可以用 for 做 getMethodX 吗? [复制]
【发布时间】:2015-06-21 18:47:31
【问题描述】:

我有四个这样创建的方法:

method1();
method2();
method3();
method4();

我可以这样用吗?

for (int i = 1; i <= 4; i++) {
    method+i+(); // ?
}

【问题讨论】:

  • 使用命令模式并将命令添加到集合中可以完成一些接近的事情。
  • method+i+() 应该做什么?
  • 他正在尝试调用名为“method”+i的方法。这是伪代码。
  • 我喜欢这个问题上出现的新的 Java8 答案。

标签: java methods


【解决方案1】:

您可以使用 Reflection 这样做,但这有点糟糕。

Class<TheClassThatHasSuchMethods> clazz = this.getClass();
for (int i=0; i < 4; i++) {
   Method method = clazz.getMethod("method" + i);
   method.invoke(this);
}

准备好处理大量异常

【讨论】:

  • 假设很多东西:它们是实例方法,公共的,它们被放置在“this”所属的类中。
【解决方案2】:

您可以使用反射。反射很棘手,而且效果不佳,因此您应该考虑一下这是否是您真正想要继续的方式。

但是,代码看起来像

for (int i = 1 ; i <= 4; i++) {
    Method method = this.getClass().getDeclaredMethod("method"+i);
    method.invoke(this);
}

假设方法不是静态的并且在当前类中定义。

【讨论】:

    【解决方案3】:

    有很多方法可以做到这一点,但总的来说,这表明您的程序结构不正确。你可以这样做。

    for (int i = 1; i <= n; i++)
        getClass().getMethod("method" + i).invoke();
    

    或者您可以只使用一个长方法来组合您需要的所有功能。

    Java 8 中的另一种方法是这样做

    Runnable[] runs = {
      this::methodOne,
      this::methodTwo,
      this::methodThree,
      this::methodFour,
      this::methodFive,
      this::methodSix };
    
    for (int i = 0; i < n; i++)
        runs[i].run();
    

    【讨论】:

    • 我总共有 6 种方法。如果 n=2 我必须运行 2 个方法,如果 n=4 4 个方法 ecc。这是我的问题。并且方法有一些参数
    • @pippo15 添加了无反射替代方案。
    • 除了Runnable之外,JDK中不是还有一个@FunctionalInterface可以做到这一点吗?
    【解决方案4】:

    如果您使用的是 Java 8,则可以将方法引用放入 Map,然后按名称访问它们。

    假设您的方法在这样的类中:

    public class Test
    {
       public void method1() { System.out.println("Method 1!"); }
       public void method2() { System.out.println("Method 2!"); }
       public void method3() { System.out.println("Method 3!"); }
       public void method4() { System.out.println("Method 4!"); }
    }
    

    关键是方法名。

    Map<String, Runnable> methodMap = new HashMap<String, Runnable>();
    Test test = new Test();
    methodMap.put("method1", test::method1);
    methodMap.put("method2", test::method2);
    methodMap.put("method3", test::method3);
    methodMap.put("method4", test::method4);
    
    for (int i = 1; i <= 4; i++)
    {
        String methodName = "method" + i;
        Runnable method = methodMap.get(methodName);
        method.run();
    }
    

    输出:

    Method 1!
    Method 2!
    Method 3!
    Method 4!
    

    如果您的方法采用一些参数和/或返回一个值,那么您将需要选择不同于Runnable 的不同功能接口。

    • Supplier 或 [Boolean|Int|Double|Long]Supplier 不带参数返回值。
    • Consumer 或 [Boolean|Int|Double|Long]Consumer 接受参数而不返回值。
    • 各种类似Function 的接口,用于获取参数和返回函数。

    如果做不到这一点,您始终可以定义自己的函数式接口来表示适合您的方法的参数和可能的返回值。

    【讨论】:

      猜你喜欢
      • 2018-10-01
      • 1970-01-01
      • 2016-01-28
      • 2013-05-17
      • 1970-01-01
      • 2021-08-23
      • 2023-03-05
      • 2011-05-24
      • 1970-01-01
      相关资源
      最近更新 更多