Any system property set with -Dkey=value
can be retrieved as a String using System.getProperty("key")
. But you can also get certain system properties casted to a specific type, e.g.:
Boolean.getBoolean("key"); //Returns true if value==true
Integer.getInteger("key"); //Returns value if exists & is number, else null
Long.getLong("key"); //Ditto as for Integer
Are there any other classes with a static getSomeClass(String systemPropertyKey)
method? Why don't Byte
, Float
, or Double
have them, but the other primitive wrappers do (or what might be the reason)?
If you look into the implementation of for example Boolean::getBoolean
you will notice that the wrapper types simply offer some convenience for reading System::getProperty
:
public static boolean getBoolean(String name) {
boolean result = false;
try {
result = toBoolean(System.getProperty(name));
} catch (IllegalArgumentException e) {
} catch (NullPointerException e) {
}
return result;
}
private static boolean toBoolean(String name) {
return ((name != null) && name.equalsIgnoreCase("true"));
}
The above method is only a convenience for retrieving a typed property or a default value if the given value is illegal.
By my knowledge, only the wrapper types Boolean
, Long
and Integer
offer such methods. (The String
type does for example not offer such a method, other than implied by your question.') The rational is probably the fact that these primitive types are common for properties that are handed over as a system property. You would for example not normally require a user to offer an XML structure by command line, just to name one example.
Reading a system property is a requirement that is spread all over the Java class library. One could have put a similar set of convenience methods into an internal package but I guess that the authors of the JDK libraries considered this to be a requirement to be also relevant to users outside of the JCL and made it public. In the end, the wrapper types are meant to offer some convenience for dealing with primitives. I would not know a better place than the wrapper types to put these methods.
As pointed out by Pablo, decimal values are not considered a good value for a command line property as the decimal separator it is locale dependent. Also, I cannot think of such a property used in the JCL. This would explain why a similar method is missing from Float
and Double
. Also, because byte
, short
and char
are represented at int
s at runtime, I would not see a particular use case for these values either what would explain their absence.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With