System properties

I have the suspect that this is going to be one of the least interesting post of this blog, still I think that even on how to get system properties there is something interesting to be said, if one is in the right mood.

Actually, more than the act of getting the system properties itself, I found (sort of) interesting to spend a few words on the Java data type used to provide that information. Properties is an ancient Java class that went through some heavy redesign with the Java 2 revolution, where the Collection hierarchy was introduced.

It is easy to write a method that dumps to standard output the current system settings but, as we'll see, there is some juicy lines that could be written commenting it:
void dumpSystemProperties() {
    Properties props = System.getProperties(); // 1
    Iterator<Map.Entry<Object, Object>> it = props.entrySet().iterator(); // 2
    while (it.hasNext()) { // 3
        Map.Entry entry =; // 4
        String s = entry.getValue().toString(); // 5
        if(s.length() > 0)
            System.out.println(entry.getKey() + ": " + s);
1. Asking to System to give us its properties is basically nothing more than this call. But what if we are not trusted enough to get them? A SecurityException would be what we get instead. If this code would be something more than an example in a blog, we should try/catch it. It is not mandatory to do that because SecurityException is-a RuntimeException, and Java won't complain for unhandled exceptions in this case, but in that unhappy case our code would brutally crash.
2. Having the properties available, usually we want to iterate on them. An alternative is represented by getting just one property, specified by its name, calling System.getProperty().
The Iterator is declared in an unusually complex way. Properties is-a Hashtable, a legacy collection pre-version 2 that we shouldn't use anymore in our code, but still available for the usual infamous compatibility reasons. In any case, Hashtable has been redesigned to be implemented in terms of Map. That leads to the fact that its key-value elements are now available as Map.Entry (internal interface of Map) instances. We know that both key and value are expected to be Strings but still we have to use a couple of Objects, again for compatibility.
Then we have to go through a call to entrySet() that provides us a view of the Properties as a Set, and on this set we can finally get our iterator.
3. Now we have a plain simple iterator, and we use it as we are accustomed to do, looping while there is a next.
4. As declared, the iterator returns a key-value pair, as a Map.Entry.
5. To have a bit of extra fun, I decided that I don't want to show the key associated to an empty value. Remember that value is an Object, so I convert it to a String before using it. I could have used a cast, and it should be safe by definition, still there is nothing bad in being a bit paranoic, so I used toString().

No comments:

Post a Comment