亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用反射調用靜態方法

使用反射調用靜態方法

偶然的你 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 關注
  • 1149 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號