Java可选参数

本文翻译自:Java optional parameters

How do I use optional parameters in Java? 如何在Java中使用可选参数? What specification supports optional parameters? 什么规范支持可选参数?


#1楼

参考:https://stackoom.com/question/43De/Java可选参数


#2楼

In JDK>1.5 you can use it like this; 在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);
        }
    }
}

#3楼

There are several ways to simulate optional parameters in Java: 有几种方法可以在Java中模拟可选参数:

  1. Method overloading. 方法重载。

     void foo(String a, Integer b) { //... } void foo(String a) { foo(a, 0); // here, 0 is a default value for b } foo("a", 2); foo("a"); 

    One of the limitations of this approach is that it doesn't work if you have two optional parameters of the same type and any of them can be omitted. 这种方法的一个限制是,如果您有两个相同类型的可选参数并且可以省略任何参数,则它不起作用。

  2. Varargs. 可变参数。

    a) All optional parameters are of the same type: 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) Types of optional parameters may be different: 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"); 

    The main drawback of this approach is that if optional parameters are of different types you lose static type checking. 这种方法的主要缺点是,如果可选参数属于不同类型,则会丢失静态类型检查。 Furthermore, if each parameter has the different meaning you need some way to distinguish them. 此外,如果每个参数具有不同的含义,您需要某种方式来区分它们。

  3. Nulls. 空值。 To address the limitations of the previous approaches you can allow null values and then analyze each parameter in a method body: 要解决先前方法的局限性,您可以允许空值,然后分析方法体中的每个参数:

     void foo(String a, Integer b, Integer c) { b = b != null ? b : 0; c = c != null ? c : 0; //... } foo("a", null, 2); 

    Now all arguments values must be provided, but the default ones may be null. 现在必须提供所有参数值,但默认值可以为null。

  4. Optional class. 可选课程。 This approach is similar to nulls, but uses Java 8 Optional class for parameters that have a default value: 此方法类似于null,但对具有默认值的参数使用Java 8 Optional类:

     void foo(String a, Optional<Integer> bOpt) { Integer b = bOpt.isPresent() ? bOpt.get() : 0; //... } foo("a", Optional.of(2)); foo("a", Optional.<Integer>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. 更新:Java 8包含类java.util.Optional开箱即用,因此在Java 8中不需要为此特殊原因使用guava。方法名称有点不同。

  5. Builder pattern. 生成器模式。 The builder pattern is used for constructors and is implemented by introducing a separate Builder class: 构建器模式用于构造函数,并通过引入单独的Builder类来实现:

      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(); 
  6. 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: 在Java 9中,这种方法变得更容易:

      @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")); 

Please note that you can combine any of these approaches to achieve a desirable result. 请注意,您可以结合使用这些方法中的任何一种来获得理想的结果。


#4楼

Default arguments can not be used in Java. 默认参数不能在Java中使用。 Where in C#, C++ and Python, we can use them.. 在C#,C ++和Python中,我们可以使用它们..

In Java, we must have to use 2 methods (functions) instead of one with default parameters. 在Java中,我们必须使用2个方法(函数)而不是使用默认参数的方法。

Example: 例:

Stash(int size); 

Stash(int size, int initQuantity);

http://parvindersingh.webs.com/apps/forums/topics/show/8856498-java-how-to-set-default-parameters-values-like-c- http://parvindersingh.webs.com/apps/forums/topics/show/8856498-java-how-to-set-default-parameters-values-like-c-


#5楼

It would depends on what you want to achieve, varargs or method overloading should solve most scenarios. 这取决于你想要实现的目标,varargs或方法重载应该解决大多数情况。 Here some nice examples of how to use them: 这里有一些很好的例子,说明如何使用它们:

http://blog.sleekface.com/in/java-core/method-with-optional-parameters/ http://blog.sleekface.com/in/java-core/method-with-optional-parameters/

but keep in mind not to over use method overloading. 但请记住不要过度使用方法重载。 it brings confusion. 它带来了混乱。


#6楼

There is optional parameters with Java 5.0. Java 5.0有可选参数。 Just declare your function like this: 只需声明你的函数:

public void doSomething(boolean... optionalFlag) {
    //default to "false"
    //boolean flag = (optionalFlag.length >= 1) ? optionalFlag[0] : false;
}

you could call with doSomething(); 你可以用doSomething();调用doSomething(); or doSomething(true); doSomething(true); now. 现在。

发布了0 篇原创文章 · 获赞 8 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/asdfgh0077/article/details/105448875
今日推荐