First, make sure that the methods you want to put into the list are of the same function type. Roughly speaking, this means that they accept the same number of parameters, and their parameter types and return types are all compatible with each other. If they aren't, then you don't really have a way of calling them afterwards, so that's not very useful.
Then, find a functional interface that represents your function type. Create a List
of that interface. There are many built-in ones. For your python examples, they all take a String
and return an int
, so a ToIntFunction<String>
is suitable.
Assuming that staticMethod1
, staticMethod2
and staticMethod3
are static methods declared in SomeClass
, you can do:
List<ToIntFunction<String>> myMethods = List.of(
SomeClass::staticMethod1, SomeClass::staticMethod2, SomeClass::staticMethod3
);
To run them you just need to get a ToIntFunction<String>
from the list (e.g. by looping), then call the applyAsInt
method:
for (ToIntFunction<String> method : myMethods) {
method.applyAsInt("hello");
}
Note that a different functional interface could have a different name for the method that you need to call to in order to run it.
If you can't find a suitable functional interface for your function type in the JDK, you can make one yourself. It's just an interface with a single method. For example, here is one for methods that take 4 ints and return nothing:
interface IntConsumer4 {
void accept(int i, int j, int k, int n);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…