1

I have use case, where I have two static functions in two different classes. Now I want to call one of this functions dynamically.

I know how to create instance of class dynamically (by class.forName()), But since I'm dealing with static functions I don't need to create an instance, So is there any way I can call this static functions dynamically ?

  • in fact, if this is about just two functions, maybe your use-case allows calling either one or another directly based on a condition, instead of passing class and method to a single execution point – Petr Kozelka Aug 14 '20 at 13:01

1 Answers1

1

You really don't need instance. Here is how to call method xyz with one String and one boolean parameter using reflections (=dynamically as you call it):

      try {
          final Class<?> clazz = MyNiceClass.class;
          final Method method = clazz.getMethod("xyz", String.class, boolean.class);
          final Object result = method.invoke(null, "hello", true);
          // do something with result
      } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
          e.printStackTrace();
      }

Notice the use of null in place of instance.

Petr Kozelka
  • 7,670
  • 2
  • 29
  • 44