Home > Net >  How to create a list of class names and iterate throught the static methoc in it?
How to create a list of class names and iterate throught the static methoc in it?

Time:03-20

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?

CodePudding user response:

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]
  • Related