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);
1void 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
20foo("a");
21foo("a", 1);
22foo("a", 1, "b2");
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 class Foo {
2 private final String a;
3 private final Integer b;
4
5 Foo(String a, Integer b) {
6 this.a = a;
7 this.b = b;
8 }
9
10 //...
11 }
12
13 class FooBuilder {
14 private String a = "";
15 private Integer b = 0;
16
17 FooBuilder setA(String a) {
18 this.a = a;
19 return this;
20 }
21
22 FooBuilder setB(Integer b) {
23 this.b = b;
24 return this;
25 }
26
27 Foo build() {
28 return new Foo(a, b);
29 }
30 }
31
32 Foo foo = new FooBuilder().setA("a").build();
1void foo(String a, Integer b, Integer c) {
2 b = b != null ? b : 0;
3 c = c != null ? c : 0;
4 //...
5}
6
7foo("a", null, 2);
1void foo(Map<String, Object> parameters) {
2 String a = "";
3 Integer b = 0;
4 if (parameters.containsKey("a")) {
5 if (!(parameters.get("a") instanceof Integer)) {
6 throw new IllegalArgumentException("...");
7 }
8 a = (Integer)parameters.get("a");
9 }
10 if (parameters.containsKey("b")) {
11 //...
12 }
13 //...
14}
15
16foo(ImmutableMap.<String, Object>of(
17 "a", "a",
18 "b", 2,
19 "d", "value"));