如何從 Java 中類的外部訪問類在內部私有方法?


您可使用 java 反射包訪問類的私有方法。

步驟 1 − 透過傳遞被宣告為私有方法的方法名稱,例項化Method 類的java.lang.reflect包。

步驟 2 − 透過將值true 傳遞到setAccessible()方法,設定方法可訪問。

步驟 3 − 最後,使用invoke()方法呼叫該方法。

示例

import java.lang.reflect.Method;

public class DemoTest {
   private void sampleMethod() {
      System.out.println("hello");
   }
}

public class SampleTest {
   public static void main(String args[]) throws Exception {
      Class c = Class.forName("DemoTest");
      Object obj = c.newInstance();
      Method method = c.getDeclaredMethod("sampleMethod", null);
      method.setAccessible(true);
      method.invoke(obj, null);
   }
}

更新日期: 2020 年 2 月 18 日

6K 多次觀看

開啟您的 職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.