I have list of classes:
List<Class<?>> = Array.asList(ClassA, ClassB, ClassC, ClassD);
each of them has a static method staticMethod(byte[] bytes)
How can I iterate through this list of classes and calling the staticMethod?
Advertisement
Answer
Represent your List like lambda expressions for your static methods.
List<Consumer<byte[]>> functionsList = Arrays.asList(ClassA::staticMethod, ClassB::staticMethod); byte[] bytes = new byte[] {1, 2, 3, 4, 5}; functionsList.forEach(consumer -> consumer.accept(bytes));
Full code:
import java.util.Arrays; import java.util.List; import java.util.function.Consumer; public class Main { public static void main(String args[]){ List<Consumer<byte[]>> functionsList = Arrays.asList(ClassA::staticMethod, ClassB::staticMethod); byte[] bytes = new byte[] {1, 2, 3, 4, 5}; functionsList.forEach(consumer -> consumer.accept(bytes)); } } public class ClassA { public static void staticMethod(byte[] bytes) { System.out.println("ClassA.staticMethod(byte[] bytes)" + Arrays.toString(bytes)); } } public class ClassB { public static void staticMethod(byte[] bytes) { System.out.println("ClassB.staticMethod(byte[] bytes)" + Arrays.toString(bytes)); } }
Output:
ClassA.staticMethod(byte[] bytes)[1, 2, 3, 4, 5] ClassB.staticMethod(byte[] bytes)[1, 2, 3, 4, 5]
EDIT: Example for methods with return value:
import java.util.Arrays; import java.util.List; import java.util.function.Function; public class Main { public static void main(String args[]){ byte[] bytes = new byte[] {1, 2, 3, 4, 5}; List<Function<byte[], String>> functionsList = Arrays.asList(ClassA::staticMethodWithReturn, ClassB::staticMethodWithReturn); functionsList.forEach(function -> { String returnValue = function.apply(bytes); } ); } } public class ClassA { public static String staticMethodWithReturn(byte[] bytes) { return ""; } } public class ClassB { public static String staticMethodWithReturn(byte[] bytes) { return ""; } }