Java SecurityManager getSecurityContext() 方法



描述

Java SecurityManager getSecurityContext() 方法建立一個封裝當前執行環境的物件。此方法的結果例如被三個引數的 checkConnect 方法和兩個引數的 checkRead 方法使用。這些方法是必要的,因為可能需要呼叫受信任的方法來代表另一個方法讀取檔案或開啟套接字。受信任的方法需要確定另一個(可能是不可信的)方法是否允許自行執行操作。此方法的預設實現是返回一個 AccessControlContext 物件。

宣告

以下是java.lang.SecurityManager.getSecurityContext() 方法的宣告

public Object getSecurityContext()

引數

返回值

此方法返回一個依賴於實現的物件,該物件封裝了有關當前執行環境的足夠資訊,以便稍後執行一些安全檢查。

異常

示例

我們的示例需要阻止每個命令的許可權。設定了一個新的策略檔案,只允許建立和設定我們的 SecurityManager。該檔案位於 C:/java.policy,包含以下文字:

grant {
   permission java.lang.RuntimePermission "setSecurityManager";
   permission java.lang.RuntimePermission "createSecurityManager";
   permission java.lang.RuntimePermission "usePolicy";
};

以下示例演示了 lang.SecurityManager.getSecurityContext() 方法的用法。

package com.tutorialspoint;

public class SecurityManagerDemo {

   public static void main(String[] args) {

      // set the policy file as the system securuty policy
      System.setProperty("java.security.policy", "file:/C:/java.policy");

      // create a security manager
      SecurityManager sm = new SecurityManager();

      // set the system security manager
      System.setSecurityManager(sm);

      // get the security context
      Object con = sm.getSecurityContext();

      // print the class context
      System.out.println("" + con);
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Exception in thread "main" java.lang.UnsupportedOperationException: The Security Manager is deprecated and will be removed in a future release
	at java.base/java.lang.System.setSecurityManager(System.java:430)
	at com.tutorialspoint.SecurityManagerDemo.main(SecurityManagerDemo.java:14)

注意 - SecurityManager 自 17 版本起已棄用,並標記為將被移除。

java_lang_securitymanager.htm
廣告
© . All rights reserved.