Java SecurityManager getClassContext() 方法



描述

Java SecurityManager getClassContext() 方法返回當前執行棧作為類陣列。陣列的長度是執行棧上方法的數量。索引 0 處的元素是當前正在執行的方法的類,索引 1 處的元素是該方法的呼叫者的類,依此類推。

宣告

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

protected Class[] getClassContext()

引數

返回值

此方法返回執行棧。

異常

示例

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

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

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

package com.tutorialspoint;

public class SecurityManagerDemo extends SecurityManager {

   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
      SecurityManagerDemo sm = new SecurityManagerDemo();

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

      // get the class context
      Class[] con = sm.getClassContext();

      // print the class context
      for (int i = 0; i < con.length; i++) {
         System.out.println("" + con[i]);
      }
   }
}

輸出

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

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)

注意 - 從版本 17 開始,安全管理器已棄用,並標記為將被移除。

java_lang_securitymanager.htm
廣告

© . All rights reserved.