英文:
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<?> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论