为了账号安全,请及时绑定邮箱和手机立即绑定

使用反射调用静态方法

使用反射调用静态方法

偶然的你 2019-10-17 11:20:05
我想调用main静态的方法。我得到了类型的对象Class,但是我无法创建该类的实例,也无法调用该static方法main。
查看完整描述

3 回答

?
神不在的星期二

TA贡献1963条经验 获得超6个赞

// 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)方法对象。


查看完整回答
反对 回复 2019-10-17
?
白衣染霜花

TA贡献1796条经验 获得超10个赞

从Method.invoke()的Javadoc中:


如果基础方法是静态的,则忽略指定的obj参数。它可以为空。

当你会发生什么


类别klass = ...;

方法m = klass.getDeclaredMethod(methodName,paramtypes);

m.invoke(null,args)


查看完整回答
反对 回复 2019-10-17
?
慕容3067478

TA贡献1773条经验 获得超3个赞

String methodName= "...";

String[] args = {};


Method[] methods = clazz.getMethods();

for (Method m : methods) {

    if (methodName.equals(m.getName())) {

        // for static methods we can use null as instance of class

        m.invoke(null, new Object[] {args});

        break;

    }

}


查看完整回答
反对 回复 2019-10-17
  • 3 回答
  • 0 关注
  • 1063 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信