:: (double colon) operator in Java 8

前端 未结 17 3247
旧时难觅i
旧时难觅i 2020-11-21 11:10

I was exploring the Java 8 source and found this particular part of code very surprising:

//defined in IntPipeline.java
@Override
public fin         


        
17条回答
  •  北荒
    北荒 (楼主)
    2020-11-21 12:01

    Yes, that is true. The :: operator is used for method referencing. So, one can extract static methods from classes by using it or methods from objects. The same operator can be used even for constructors. All cases mentioned here are exemplified in the code sample below.

    The official documentation from Oracle can be found here.

    You can have a better overview of the JDK 8 changes in this article. In the Method/Constructor referencing section a code example is also provided:

    interface ConstructorReference {
        T constructor();
    }
    
    interface  MethodReference {
       void anotherMethod(String input);
    }
    
    public class ConstructorClass {
        String value;
    
       public ConstructorClass() {
           value = "default";
       }
    
       public static void method(String input) {
          System.out.println(input);
       }
    
       public void nextMethod(String input) {
           // operations
       }
    
       public static void main(String... args) {
           // constructor reference
           ConstructorReference reference = ConstructorClass::new;
           ConstructorClass cc = reference.constructor();
    
           // static method reference
           MethodReference mr = cc::method;
    
           // object method reference
           MethodReference mr2 = cc::nextMethod;
    
           System.out.println(cc.value);
       }
    }
    

提交回复
热议问题