Java中的类 getProtectionDomain() 方法和示例
Java.lang.Class 类的getProtectionDomain()方法用于获取该类的ProtectionDomain。该方法以ProtectionDomain 对象的形式返回该类的指定ProtectionDomain。
句法:
public ProtectionDomain getProtectionDomain()
参数:此方法不接受任何参数
返回值:该方法以ProtectionDomain对象的形式返回该类的指定ProtectionDomain 。
异常此方法抛出:
- 如果安全管理器存在且其 checkPermission 方法不允许获取 ProtectionDomain,则出现 SecurityException。
下面的程序演示了 getProtectionDomain() 方法。
示例 1:
// Java program to demonstrate
// getProtectionDomain() method
import java.util.*;
public class Test {
public Object obj;
public static void main(String[] args)
throws ClassNotFoundException
{
try {
// returns the Class object for this class
Class myClass = Class.forName("Test");
System.out.println("Class represented by myClass: "
+ myClass.toString());
// Get the ProtectionDomain of myClass
// using getProtectionDomain() method
System.out.println("ProtectionDomain of myClass: "
+ myClass.getProtectionDomain());
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
Class represented by myClass: class Test
java.security.AccessControlException: access denied ("java.lang.RuntimePermission" "getProtectionDomain")
示例 2:
// Java program to demonstrate
// getProtectionDomain() method
import java.util.*;
class Main {
private Object obj;
public static void main(String[] args)
throws ClassNotFoundException, NoSuchFieldException
{
try {
// returns the Class object for this class
Class myClass = Class.forName("Main");
System.out.println("Class represented by myClass: "
+ myClass.toString());
String ProtectionDomainName = "obj";
// Get the ProtectionDomain of myClass
// using getProtectionDomain() method
System.out.println("ProtectionDomain of myClass: "
+ myClass.getProtectionDomain());
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
Class represented by myClass: class Main
java.security.AccessControlException: access denied ("java.lang.RuntimePermission" "getProtectionDomain")
参考: https://docs.oracle.com/javase/9/docs/api/ Java/lang/Class.html#getProtectionDomain–