Getting an integer from a system property (parameter starting with -D
) in Java is very easy.
Integer getInteger (String, int) Just use the method.
Demo.java
public class Demo {
//In this sample myapp.loop.Let it be a system property called count
private static final String SYSTEM_PROP_KEY = "myapp.loop.count";
public static void main(String[] args) {
//★ Point
Integer count = Integer.getInteger(SYSTEM_PROP_KEY, 10);
String value = "";
for (int i = 0; i < count; i++) {
value = value + "*";
System.out.println(value);
}
}
}
** ★ Point ** The first argument is the system property key (character string), and the second argument is the default value. The default value is applied when the system property is not set or when the set value cannot be converted to Integer.
Try it out
C:\temp>javac Demo.java
C:\temp>java Demo
*
**
***
****
*****
******
*******
********
*********
**********
C:\temp>java -Dmyapp.loop.count=5 Demo
*
**
***
****
*****
C:\temp>java -Dmyapp.loop.count=x Demo
*
**
***
****
*****
******
*******
********
*********
**********
C:\temp>
The first is when no system properties have been set. In this case, the default value is 10.
The second time is when 5 is set in the system properties. In this case, 5 is set firmly.
The last is when you set the system property to a value that cannot be converted to an Integer (x in the example). Again, the default value is 10.
If you want to get an integer from a system property, take the trouble to System.getProperty (String) It's easy because you don't have to use .lang.String-)!
The following is an article for newcomers. For your reference.
Recommended Posts