方法引用在Java8.0中一共定义了四种形式:
·引用静态方法:类名称::static 方法名称;
·引用某个对象的方法:实例化对象::普通方法;
·引用特定类型的方法:特定类::普通方法;
·引用构造方法:类名称::new
范例1:引用静态方法
interface Message<P, R> {
public R transFrom(P p);
}
public class Demo {
public static void main(String[] args) {
Message<String, Integer> msg = Integer::parseInt;
int temp = msg.transFrom("200") * 40;
System.out.println(temp);
}
}
=============分割线=============
范例2:普通方法引用
interface Message<R> {
public R upper();
}
public class Demo {
public static void main(String[] args) {
Message<String> msg = "hello".substring(0, 4)::toUpperCase;
String str = msg.upper();
System.out.println(str);
}
}
=============分割线=============
范例3:特定类方法引用
interface Message<P> {
public int compare(P p1, P p2);
}
public class Demo {
public static void main(String[] args) {
Message<String> msg = String::compareTo;
System.out.println(msg.compare("A", "B"));
}
}
=============分割线=============
范例4:构造方法
interface Message<C> {
public C create(String str, double num);
}
class Book {
private String title;
private double price;
public Book(String title, double price) {
this.title = title;
this.price = price;
}
@Override
public String toString() {
return "书名:《" + this.title + "》,价格:" + this.price + "元。";
}
}
public class Demo {
public static void main(String[] args) {
Message<Book> msg = Book::new;
Book bookA = msg.create("Java从入门到精通", 88.8);
Book bookB = msg.create("Oracle从入门到精通", 99.9);
System.out.println(bookA);
System.out.println(bookB);
}
}
