简体   繁体   English

如何存储 void 方法的数组列表

[英]how can I store an arraylist of void methods

Is it possible to store void type methods in an arrayList or can you only store methods that have a return value?是否可以将 void 类型的方法存储在 arrayList 中,或者只能存储具有返回值的方法? I want to call any one of up to 15 methods and rather than write:我想调用最多 15 种方法中的任何一种,而不是这样写:

if(var == 1){
    method1()
}else if(var ==2){
    method2();
}

etc...等等...

by the time you surround with try/catch and a few more lines of code (that repeat for each one) it would be much neater if you could do:当你用 try/catch 和几行代码(对每一行重复)时,如果你能这样做会更整洁:

arrayList.get(var); //or something similar

However my methods just "do stuff" as opposed to return a value so if the methods themselves cannot be stored in an array is there somewhere else they can be stored together and extracted with a for loop or by just using the "var" integer?然而,我的方法只是“做事”而不是返回一个值,所以如果方法本身不能存储在数组中,是否还有其他地方可以将它们存储在一起并使用 for 循环或仅使用“var”整数提取?

What you are asking for is given precisely by你所要求的正是由

java.util.ArrayList<java.lang.reflect.Method>

but it seems to me you should be using a switch statement.但在我看来你应该使用 switch 语句。

To anyone who comes to look at this post 6 years later like I was, I suggest you have your ArrayList return a String of "" .对于 6 年后像我一样来看这篇文章的人,我建议你让你的ArrayList返回一个字符串"" If the value is not used, it wont matter whether it's there or not, but you'll need it to make the compiler happy.如果未使用该值,则它是否存在无关紧要,但是您需要它来使编译器满意。

You cannot store method references in Java.您不能在 Java 中存储方法引用。

However, you can create an object of a class that has a defined interface that allows you to invoke the method readily.但是,您可以创建一个具有定义接口的类的对象,该接口允许您轻松调用该方法。

public interface VoidMethod {
  public void callMethod();
}

// ...

public class Method1 implements VoidMethod {
  public void callMethod() {
    // your stuff here
  }
}

// ...

public class MethodN implements VoidMethod {
  public void callMethod() {
    // your stuff here
  }
}

Then you can populate an object array with instances of VoidMethod.然后,您可以使用 VoidMethod 的实例填充对象数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM