AskHandle Blog
Is it Possible to Call Methods of a Class Dynamically Using an Object Property?

Is it Possible to Call Methods of a Class Dynamically Using an Object Property?
In object-oriented programming, methods are functions defined within a class that perform actions on objects of that class. Typically, calling a method requires knowing its name. Yet, there are cases where you may want to call a method dynamically based on an object's property. This article explores the possibility of achieving this in different programming languages.
Dynamic Method Invocation in Programming Languages
1. Python
Python, a dynamically-typed language, allows dynamic method invocation. You can use the getattr() function to retrieve a method by its name, represented as a string, and then call it. Here’s an example:
1class MyClass:
2 def method1(self):
3 print("Method 1")
4
5 def method2(self):
6 print("Method 2")
7
8obj = MyClass()
9method_name = "method1"
10method = getattr(obj, method_name)
11method() # Output: Method 12. JavaScript
JavaScript also supports dynamic method invocation. You can access an object's method using square brackets and a string for the method name. Here's an example:
1class MyClass {
2 method1() {
3 console.log("Method 1");
4 }
5
6 method2() {
7 console.log("Method 2");
8 }
9}
10
11const obj = new MyClass();
12const methodName = "method1";
13obj[methodName](); // Output: Method 13. Java
Java, a statically-typed language, does not have built-in support for dynamic method invocation using object properties. Yet, you can use reflection to achieve similar functionality. Here's an example:
1import java.lang.reflect.Method;
2
3class MyClass {
4 public void method1() {
5 System.out.println("Method 1");
6 }
7
8 public void method2() {
9 System.out.println("Method 2");
10 }
11}
12
13public class Main {
14 public static void main(String[] args) throws Exception {
15 MyClass obj = new MyClass();
16 String methodName = "method1";
17 Method method = obj.getClass().getMethod(methodName);
18 method.invoke(obj); // Output: Method 1
19 }
20}Dynamically-typed languages like Python and JavaScript allow dynamic method invocation using an object property. In contrast, statically-typed languages like Java require reflection to achieve this functionality. Dynamic method invocation offers flexibility in scenarios where method names may vary, such as user input or runtime conditions.