javasecurity-policy

Java security policy set from code


Using this bit of code to try and set a policy file:

ClassLoader cl= getClass().getClassLoader();
URL policyURL =cl.getResource("res/policy/new_policy.policy");
System.setProperty("java.security.policy", policyURL.toString());

And I get a java.lang.NullPointerException on the last line. The file is in my project directory in the correct path.

Question: What could cause this exception?

Answer: Running from eclipse, the path was constructed relative to the main project folder, not the project's bin folder. Considering that, moving the res folder in the bin folder solved the issue without changing any of the code above.


Solution

  • If the path is in you project, add a /

    cl.getResource("/res/policy/new_policy.policy")
    

    But I would suggest you print the value of policyURL to check that you retrieve the file ok.

    If you are executing in Eclipse, remember that the resources must be in a resources folder so they go to classes folder when build.

    Eclipse only execute classes, and the classes live in output folder (bin).