Avatar ·

How to call a Java method by its string name (reflection)?

Hello everyone! I'm new to Java and I've encountered a problem: I have a string containing a method name, and I need to call that method on an object. For example, I have a Calculator class with methods add, subtract, multiply. The user enters the operation name from the console (the string "add", "subtract", etc.), and I need to execute the corresponding method. I don't want to write a long switch-case or if-else for a dozen methods — it's ugly and inflexible. How can I do this? I've heard there is something called "reflection", but I don't understand how to apply it. My current code looks like this: ```java public class Calculator { public int add(int a, int b) { return a + b; } public int subtract(int a, int b) { return a - b; } public int multiply(int a, int b) { return a * b; } } public clas