簡體   English   中英

如何限制開發人員使用反射來訪問Java中的私有方法和構造函數?

[英]How to restrict developers to use reflection to access private methods and constructors in Java?

如何限制開發人員使用反射來訪問Java中的私有方法和構造函數?

使用普通的Java代碼,我們無法在類外部訪問私有構造函數或私有方法。 但是通過使用反射,我們可以訪問Java類中的任何私有方法和構造函數。

那么,如何為Java代碼賦予安全性呢?

使用SecurityManager和足夠嚴格的安全策略運行您的應用程序。

教程中簡短摘要, 安全文檔中有大量信息。

在所有私有方法/構造函數中添加checkPermission()方法。 通過assert callerClass=selfClass sun.reflect.Reflection.getCallerClass(int n)callerClass=selfClass

getCallerClass返回方法realFramesToSkip框架類(從零開始),而忽略與java.lang.reflect.Method.invoke()及其實現相關聯的框架。 第一幀是一個與該方法相關聯,因此getCallerClass(0)返回該類對象sun.reflect.Reflection

public class PrivateConstructorClass {

    private PrivateConstructorClass() {
        checkPerMission();
              //you own code go below
    }

    void checkPerMission() {
        Class self = sun.reflect.Reflection.getCallerClass(1);
        Class caller = sun.reflect.Reflection.getCallerClass(3);
        if (self != caller) {
            throw new java.lang.IllegalAccessError();
        }
    }
}

您可以嘗試測試反射,它將失敗:

public class TestPrivateMain {

    Object newInstance() throws Exception {

        final Class<?> c = Class.forName("package.TestPrivate");

        final Constructor<?> constructor = c.getDeclaredConstructor();
        constructor.setAccessible(true);
        return constructor.newInstance();

    }

    public static void main(String[] args) throws Exception {
        Object t = new TestPrivateMain().newInstance();
    }
} 

您(作為相關代碼的開發人員)無法做到這一點。

運行該應用程序的最終用戶可以安裝一個禁止反射的SecurityManager。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM