AccessController.doPrivileged

后端 未结 1 701
我寻月下人不归
我寻月下人不归 2020-12-03 13:56

I am trying to figure out what some legacy code is doing. What exactly is this line doing, and why would I need it this way?

String lineSeparator = (String)          


        
相关标签:
1条回答
  • 2020-12-03 14:24

    It is just getting a system property. Retrieving system properties requires permissions which the calling code may not have. The doPrivileged asserts the privileges of the calling class irrespective of how it was called. Clearly, doPrivileged is something you need to be careful with.

    The code quoted is the equivalent of:

    String lineSeparator = java.security.AccessController.doPrivileged(
        new java.security.PrivilegedAction<String>() {
            public String run() {
                return System.getProperty("line.separator");
            }
        }
     );
    

    (Don't you just love the conciseness of Java's syntax?)

    Without asserting privileges, this can be rewritten as:

    String lineSeparator = System.getProperty("line.separator");
    
    0 讨论(0)
提交回复
热议问题