什么规范支持可选参数?
当前回答
在Java中有几种模拟可选参数的方法:
方法重载。 void foo(字符串a,整数b) { / /…… } void foo(字符串a) { foo (0);//这里,0是b的默认值 } foo (" a ", 2); foo(“a”);
这种方法的局限性之一是,如果有两个相同类型的可选参数,并且可以省略其中任何一个,则该方法将不起作用。
瓦拉格斯。
a)所有可选参数类型相同:
void foo(String a, Integer... b) {
Integer b1 = b.length > 0 ? b[0] : 0;
Integer b2 = b.length > 1 ? b[1] : 0;
//...
}
foo("a");
foo("a", 1, 2);
b)可选参数类型可能不同:
void foo(String a, Object... b) {
Integer b1 = 0;
String b2 = "";
if (b.length > 0) {
if (!(b[0] instanceof Integer)) {
throw new IllegalArgumentException("...");
}
b1 = (Integer)b[0];
}
if (b.length > 1) {
if (!(b[1] instanceof String)) {
throw new IllegalArgumentException("...");
}
b2 = (String)b[1];
//...
}
//...
}
foo("a");
foo("a", 1);
foo("a", 1, "b2");
这种方法的主要缺点是,如果可选参数的类型不同,则会丢失静态类型检查。此外,如果每个参数具有不同的含义,则需要某种方法来区分它们。
null。为了解决前面方法的局限性,你可以允许空值,然后在方法体中分析每个参数: void foo(字符串a,整数b,整数c) { B = B != null ?B: 0; C = C != null ?C: 0; / /…… } Foo ("a", null, 2);
现在必须提供所有参数值,但默认值可能为空。
Optional class. This approach is similar to nulls, but uses Java 8 Optional class for parameters that have a default value: void foo(String a, Optional bOpt) { Integer b = bOpt.isPresent() ? bOpt.get() : 0; //... } foo("a", Optional.of(2)); foo("a", Optional.absent()); Optional makes a method contract explicit for a caller, however, one may find such signature too verbose. Update: Java 8 includes the class java.util.Optional out-of-the-box, so there is no need to use guava for this particular reason in Java 8. The method name is a bit different though. Builder pattern. The builder pattern is used for constructors and is implemented by introducing a separate Builder class: 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(); Maps. When the number of parameters is too large and for most of the default values are usually used, you can pass method arguments as a map of their names/values: void foo(Map<String, Object> parameters) { String a = ""; Integer b = 0; if (parameters.containsKey("a")) { if (!(parameters.get("a") instanceof Integer)) { throw new IllegalArgumentException("..."); } a = (Integer)parameters.get("a"); } if (parameters.containsKey("b")) { //... } //... } foo(ImmutableMap.<String, Object>of( "a", "a", "b", 2, "d", "value")); In Java 9, this approach became easier: @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"));
请注意,您可以结合使用这些方法中的任何一种来获得理想的结果。
其他回答
在JDK>1.5中,你可以这样使用它;
public class NewClass1 {
public static void main(String[] args) {
try {
someMethod(18); // Age : 18
someMethod(18, "John Doe"); // Age & Name : 18 & John Doe
} catch (Exception e) {
e.printStackTrace();
}
}
static void someMethod(int age, String... names) {
if (names.length > 0) {
if (names[0] != null) {
System.out.println("Age & Name : " + age + " & " + names[0]);
}
} else {
System.out.println("Age : " + age);
}
}
}
Java 5.0中有可选参数。只需像这样声明你的函数:
public void doSomething(boolean... optionalFlag) {
//default to "false"
//boolean flag = (optionalFlag.length >= 1) ? optionalFlag[0] : false;
}
你可以调用doSomething();或doSomething(真正的);现在。
你可以这样使用:
public void addError(String path, String key, Object... params) {
}
params变量是可选的。它被视为对象的可空数组。
奇怪的是,我在文档中找不到任何关于这个的东西,但它是有效的!
这是Java 1.5及以上版本的“新功能”(Java 1.4或更早版本不支持)。
我看到用户bhoot在下面也提到了这一点。
简短版本:
用三个点:
public void foo(Object... x) {
String first = x.length > 0 ? (String)x[0] : "Hello";
int duration = x.length > 1 ? Integer.parseInt((String) x[1]) : 888;
}
foo("Hii", );
foo("Hii", 146);
(根据@VitaliiFedorenko的回答)
VarArgs和重载已经被提到。另一种选择是Bloch Builder模式,它看起来像这样:
MyObject my = new MyObjectBuilder().setParam1(value)
.setParam3(otherValue)
.setParam6(thirdValue)
.build();
尽管这种模式最适合于在构造函数中需要可选参数的情况。
推荐文章
- javax.transaction.Transactional vs . org.springframework.transaction.annotation.Transactional
- Java 8接口方法中不允许“同步”的原因是什么?
- 如何找到Java堆大小和内存使用(Linux)?
- 使用Enum实现单例(Java)
- RabbitMQ与通道和连接之间的关系
- buildSessionFactory()配置方法在Hibernate中已弃用?
- Spring MVC -如何获得所有的请求参数在一个地图在Spring控制器?
- 如何在Java中按两个字段排序?
- 文件之间的差异。路径中的分隔符和斜杠
- 在方法参数中使用NotNull注释
- Spring MVC中处理可选参数的@RequestParam
- Tomcat:如何查找正在运行的Tomcat版本?
- “java”、“javaw”和“javaws”之间有什么区别?
- 将Date对象转换为日历对象
- 在Java中保存最后N个元素的大小有限的队列