如何从Java类的外部访问类的私有方法?

您可以使用java反射包访问类的私有方法。

步骤1-通过传递声明为私有的方法的方法名称来实例化java.lang.reflect包的Method 类。

步骤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);
   }
}