在 Java 中将 System 属性设置为 Null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4323995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set System propery to Null in Java
提问by Victoria Seniuk
In my unit tests I need to set the "workingDir" system property to Null.
在我的单元测试中,我需要将“workingDir”系统属性设置为 Null。
But I can not do somesing like this, because It give me NullPointerException:
但我不能这样做,因为它给了我 NullPointerException:
System.setProperty("workingDir", null);
How can I do it?
我该怎么做?
回答by Jon Skeet
You can't set a property to have an actual null value - you can only clear it, like this:
您不能将属性设置为具有实际空值 - 您只能清除它,如下所示:
System.clearProperty("workingDir");
回答by Martin Algesten
System.setProperty()
is internally implemented using a Properties
object, which in turn uses the good old Hashtable
. Those hashtables never let you set a null value using theput()
method, so it can't really be done that way. Jon Skeet's post has the solution.
System.setProperty()
是使用一个Properties
对象在内部实现的,而该对象又使用了旧的Hashtable
. 那些哈希表永远不会让您使用该put()
方法设置空值,因此它不能真正以这种方式完成。Jon Skeet 的帖子提供了解决方案。
回答by Vladimir Ivanov
You can't do it, as setProperty
method throws NullPointerException if any of it's arguments is null.
You can put an empty string there and check for it in your unit tests or simply clearProperty, as Jon suggested.
你不能这样做,因为setProperty
如果它的任何参数为空,方法就会抛出 NullPointerException。您可以在那里放置一个空字符串并在您的单元测试中检查它,或者像 Jon 建议的那样简单地使用 clearProperty。