class Foo {private final String a;private final Integer b;
Foo(String a, Integer b) {this.a = a;this.b = b;}
//...}
class FooBuilder {private String a = "";private Integer b = 0;
FooBuilder setA(String a) {this.a = a;return this;}
FooBuilder setB(Integer b) {this.b = b;return this;}
Foo build() {return new Foo(a, b);}}
Foo foo = new FooBuilder().setA("a").build();
地图。当参数数量太大并且通常使用大多数默认值时,您可以将方法参数作为其名称/值的映射传递:
validfoo(Map参数){//属性名字符串a="";整数b=0;if(parameters.contains键("a")){if(!(parameters.get("a")instance of Integer))抛出新的IllegalArgumentException("…");}a=(整数)parameters.get("a");}if(parameters.containsKey("b")){//…}//…}
foo(ImMutableMap.of("a","a","b",2,"d","value");
在Java9中,这种方法变得更容易:
@SuppressWarnings("unchecked")static <T> T getParm(Map<String, Object> map, String key, T defaultValue) {return (map.containsKey(key)) ? (T) map.get(key) : defaultValue;}
void foo(Map<String, Object> parameters) {String a = getParm(parameters, "a", "");int b = getParm(parameters, "b", 0);// d = ...}
foo(Map.of("a","a", "b",2, "d","value"));