使用反射调用静态方法 [英] Invoking a static method using reflection

查看:126
本文介绍了使用反射调用静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调用静态的 main 方法。我得到了类型为 Class 的对象,但我无法创建该类的实例,也无法调用 static 方法 main

I want to invoke the main method which is static. I got the object of type Class, but I am not able to create an instance of that class and also not able to invoke the static method main.

推荐答案

// String.class here is the parameter type, that might not be the case with you
Method method = clazz.getMethod("methodName", String.class);
Object o = method.invoke(null, "whatever");

如果方法是私人使用 getDeclaredMethod()而不是 getMethod()。并在方法对象上调用 setAccessible(true)

In case the method is private use getDeclaredMethod() instead of getMethod(). And call setAccessible(true) on the method object.

这篇关于使用反射调用静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆