溫馨提示×

java中如何調用private方法

小億
187
2024-03-07 17:19:25
欄目: 編程語言

在Java中,私有方法只能在其所屬的類中被調用。如果想要在其他類中調用私有方法,可以通過反射來實現。

下面是一個示例代碼,演示了如何使用反射來調用一個私有方法:

import java.lang.reflect.Method;

public class PrivateMethodExample {

    private void privateMethod() {
        System.out.println("This is a private method.");
    }

    public static void main(String[] args) throws Exception {
        PrivateMethodExample example = new PrivateMethodExample();

        // 獲取私有方法
        Method method = PrivateMethodExample.class.getDeclaredMethod("privateMethod");

        // 設置私有方法可以被訪問
        method.setAccessible(true);

        // 調用私有方法
        method.invoke(example);
    }
}

在上面的代碼中,我們首先創建了一個PrivateMethodExample類,其中包含一個私有方法privateMethod。然后在main方法中使用反射獲取私有方法,并調用它。需要注意的是,需要通過method.setAccessible(true)來設置私有方法可以被訪問。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女