引用方法
在java8中引入lambda表达式,简化了内部类的书写;有时lambda表达式中只调用了一个函数,这时就可以使用引用方法进一步简化书写 方法引用通过方法的名字来指向一个方法。 引用方法可以分成四类:
调用new方法 调用静态方法 调用特定类 任意对象 的方法:被调用对象 和 引用方法的类 类型匹配 调用特定对象的方法
public class MethodTest {
public static Car create ( final Supplier< Car> supplier) {
return supplier. get ( ) ;
}
public static void main ( String[ ] args) {
Car car= MethodTest. create ( Car: : new ) ;
List< Integer> intList= Arrays. asList ( 1 , 2 , 3 , 4 , 5 ) ;
intList. forEach ( MyUtil: : print) ;
List< Car> carList= Arrays. asList ( new Car ( "ming" ) , new Car ( "ming1" ) , new Car ( "jia" ) ) ;
carList. forEach ( Car: : printName) ;
MyUtil util= new MyUtil ( ) ;
carList. forEach ( util: : out) ;
}
}
class Car {
private String name;
public Car ( ) { }
public Car ( String name) {
this . name= name;
}
public void printName ( ) {
System. out. println ( this . name) ;
}
public String getName ( ) {
return name;
}
}
class MyUtil {
public static void print ( int i) {
System. out. println ( "int=" + i) ;
}
public void out ( Car car) {
System. out. println ( car. getName ( ) ) ;
}
}
参考:http://www.runoob.com/java/java8-method-references.html