Indexing (faster)
You can use FunctionalInterface to save methods in a container to index them. You can use array container to invoke them by numbers or hashmap to invoke them by strings. By this trick, you can index your methods to invoke them dynamically faster.
@FunctionalInterface public interface Method { double execute(int number); } public class ShapeArea { private final static double PI = 3.14; private Method[] methods = { this::square, this::circle }; private double square(int number) { return number * number; } private double circle(int number) { return PI * number * number; } public double run(int methodIndex, int number) { return methods[methodIndex].execute(number); } } Lambda syntax
You can also use lambda syntax:
public class ShapeArea { private final static double PI = 3.14; private Method[] methods = { number -> { return number * number; }, number -> { return PI * number * number; }, }; public double run(int methodIndex, int number) { return methods[methodIndex].execute(number); } } New Edit
Just now I was thinking to provide you with a universal solution to work with all possible methods with variant number of arguments:
@FunctionalInterface public interface Method { Object execute(Object ...args); } public class Methods { private Method[] methods = { this::square, this::rectangle }; private double square(int number) { return number * number; } private double rectangle(int width, int height) { return width * height; } public Method get(int methodIndex) { return methods[methodIndex]; } } Usage:
methods.get(1).execute(width, height);