Dynamically call a static function in Java

huangapple go评论71阅读模式
英文:

Dynamically call a static function in Java

问题

Sure, here's the translation:

我有一个使用情况,其中我有两个不同类中的静态函数。
现在我想要动态调用其中一个函数。

我知道如何动态创建类的实例(使用 class.forName()),但由于我在处理静态函数,所以我不需要创建实例,那么有没有办法可以动态调用这些静态函数呢?

英文:

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 ?

答案1

得分: 1

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

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 the result
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    e.printStackTrace();
}

Notice the use of null in place of an instance.

英文:

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&lt;?&gt; clazz = MyNiceClass.class;
          final Method method = clazz.getMethod(&quot;xyz&quot;, String.class, boolean.class);
          final Object result = method.invoke(null, &quot;hello&quot;, true);
          // do something with result
      } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
          e.printStackTrace();
      }

Notice the use of null in place of instance.

huangapple
  • 本文由 发表于 2020年8月14日 20:31:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/63412827.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定