1void foo(String a, Integer b) {
2 //...
3}
4
5void foo(String a) {
6 foo(a, 0); // here, 0 is a default value for b
7}
8
9foo("a", 2);
10foo("a");
1void foo(String a, Optional<Integer> bOpt) {
2 Integer b = bOpt.isPresent() ? bOpt.get() : 0;
3 //...
4}
5
6foo("a", Optional.of(2));
7foo("a", Optional.<Integer>absent());
1void foo(String a, Integer... b) {
2 Integer b1 = b.length > 0 ? b[0] : 0;
3 Integer b2 = b.length > 1 ? b[1] : 0;
4 //...
5}
6
7foo("a");
8foo("a", 1, 2);
1//Java 9 and above only
2@SuppressWarnings("unchecked")
3 static <T> T getParm(Map<String, Object> map, String key, T defaultValue)
4 {
5 return (map.containsKey(key)) ? (T) map.get(key) : defaultValue;
6 }
7
8 void foo(Map<String, Object> parameters) {
9 String a = getParm(parameters, "a", "");
10 int b = getParm(parameters, "b", 0);
11 // d = ...
12 }
13
14 foo(Map.of("a","a", "b",2, "d","value"));
1@SuppressWarnings("unchecked")
2static <T> T getParm(Map<String, Object> map, String key, T defaultValue) {
3 return (map.containsKey(key)) ? (T) map.get(key) : defaultValue;
4}
5
6void foo(Map<String, Object> parameters) {
7 String a = getParm(parameters, "a", "");
8 int b = getParm(parameters, "b", 0);
9 // d = ...
10}
11
12foo(Map.of("a","a", "b",2, "d","value"));
13
1 void foo(String a, Object... b) {
2 Integer b1 = 0;
3 String b2 = "";
4 if (b.length > 0) {
5 if (!(b[0] instanceof Integer)) {
6 throw new IllegalArgumentException("...");
7 }
8 b1 = (Integer)b[0];
9 }
10 if (b.length > 1) {
11 if (!(b[1] instanceof String)) {
12 throw new IllegalArgumentException("...");
13 }
14 b2 = (String)b[1];
15 //...
16 }
17 //...
18 }
19
20 foo("a");
21 foo("a", 1);
22 foo("a", 1, "b2");
23