java8中引入了一个新的操作符::, 是两个英文半角的冒号, 这个操作符用来引用方法, 其本质也是对接口的一种重写。
请看下面的实例:
import java.util.ArrayList; import java.util.List; /** * Created by outofmemory.cn on 2015/11/25. */ public class AppMethodReference { public static void main(String[] args) { List<String> names = new ArrayList<String>(); names.add("Bush"); names.add("Tom"); names.add("Jim"); System.out.println("print with instance method"); names.forEach(System.out::println); System.out.println("print with instance method"); AppMethodReference appMethodReference = new AppMethodReference(); names.forEach(appMethodReference::printSomething); System.out.println("print with static method"); names.forEach(AppMethodReference::printStatic); } private void printSomething(String str) { System.out.println(str); } private static void printStatic(String input) { System.out.println(input); } }
::操作符可以引用实例方法,也可以引用静态方法, 引用实例时::前面是实例, 引用静态方法时::前面是类。 上述方法输出内容如下:
print with instance method Bush Tom Jim print with instance method Bush Tom Jim print with static method Bush Tom Jim
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/10467.html