在 Java 中无法将方法直接放入数组。但可以通过以下方式实现类似的效果:1. 将方法引用存储在数组中;2. 将方法对象存储在数组中,然后调用这些方法。

如何在 Java 中将方法放入数组?
Java 不支持将方法直接放入数组中。但是,我们可以通过以下方式实现类似的效果:
1. 将方法引用存储在数组中
方法引用是指指向特定方法的指针。我们可以将方法引用存储在数组中,从而间接调用这些方法:
立即学习“Java免费学习笔记(深入)”;
// 定义一个方法接口
interface MethodInterface {
void printName(String name);
}
public class Main {
public static void main(String[] args) {
// 定义一个方法数组
MethodInterface[] methodArray = new MethodInterface[2];
// 将方法引用存储在数组中
methodArray[0] = System.out::println;
methodArray[1] = String::toUpperCase;
// 调用数组中的方法
methodArray[0].printName("Java");
methodArray[1].printName("java");
}
}2. 将方法对象存储在数组中
我们可以将方法对象存储在数组中,从而调用这些方法:
public class Main {
public static void main(String[] args) {
// 定义一个方法数组
Method[] methodArray = new Method[2];
// 获取方法对象并存储在数组中
methodArray[0] = String.class.getMethod("toUpperCase", String.class);
methodArray[1] = System.class.getMethod("println", Object.class);
// 调用数组中的方法
try {
methodArray[0].invoke("java");
methodArray[1].invoke(System.out, "Java");
} catch (Exception e) {
e.printStackTrace();
}
}
}











