A Bad Way of Getting Java System Property

I don't like code like this:
String flag1 = System.getProperties().getProperty("flag1.key");
String flag2 = System.getProperties().getProperty("flag2.key");
Why not just call System.getProperty("flag1.key")? In most cases, the two produces the same result. But the former is unnecessarily verbose.

You may be able to save some security check overhead by caching the system properties inside your application, if you need to get a series of properties, and if SecurityManager is enabled. For example,
Properties sysProps = System.getProperties();
String flag1 = sysProps.getProperty("flag1.key");
String flag2 = sysProps.getProperty("flag2.key");
...
The security check is only performed once in the above block. But it requires both read and write permission on all system properties: permission java.util.PropertyPermission "*", "read,write";

With System.getProperty("key"), security check is performed for every call. But it only requires read permission on the target property: permission java.util.PropertyPermission "key", "read";

The savings may be negligible, if any. The only time I will use System.getProperties() is when the property key is unknown, and the application needs to iterate through all system properties based on some criteria. For example,
Properties myProps = new Properties();
Properties sysProps = System.getProperties();
Set<Map.Entry<String, String>> entrySet =
sysProps.entrySet();
while(entrySet.hasNext()) {
Map.Entry entry = entrySet.next();
String key = entry.getKey();
if(key.startsWith("foo.")) {
myProps.setProperty(key, entry.getValue(key));
}
}

Followers

Pageviews Last 7 Days