:: 常常被称作为方法引用,提供了一种不执行方法的方法。使用 :: 可以进一步简化一些使用了lambda表达式的代码,让代码更加简洁。
1.省略输出
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public class Test {
public static void main(String[] args) {
List<String> list = Arrays.asList("a", "b", "c");
// 匿名内部类
list.forEach(new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
});
// lambda表达式
list.forEach(key -> System.out.println(key));
// ::方式
list.forEach(System.out::println);
}
}
2. 类的静态方法引用
import java.util.Arrays;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> list = Arrays.asList("a", "b", "c");
// 引用静态方法,通过类名+::+方法名的方式
list.forEach(Test::println);
}
public static void println(Object o) {
System.out.println(o);
}
}
3. 对象实例方法引用
import java.util.Arrays;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> list = Arrays.asList("a", "b", "c");
Test test = new Test();
// 引用实例方法,通过对象+::+方法名的方式
list.forEach(test::println);
}
public void println(Object o) {
System.out.println(o);
}
}
4. 父类方法引用
import java.util.Arrays;
import java.util.List;
public class Son extends Father {
public static void main(String[] args) {
Son son = new Son();
son.print();
}
public void print() {
List<String> list = Arrays.asList("a", "b", "c");
// 引用父类方法,通过super+::+方法名的方式
list.forEach(super::println);
}
}
class Father {
public void println(Object o) {
System.out.println(o);
}
}
5. 引用无参构造器
public class Test {
public void test() {
// 引用构造器使用类名::new
Example example = Test::new;
Test test = example.create();
System.out.println(test);
}
public static void main(String[] args) {
Test test = new Test();
test.test();
}
}
interface Example {
Test create();
}
- 引用有参构造器
public class Test {
String name;
public Test(String name) {
this.name = name;
}
public static void main(String[] args) {
// 构造器的参数要和接口的参数保持一致,同样使用类名+::+new的方式来引用
Example example = Test::new;
Test test = example.create("a,b,c");
System.out.println(test.name);
}
}
interface Example {
Test create(String name);
}