您的位置:首页 > 编程语言 > Java开发

Java 8.0新增特性(方法引用)

2018-03-18 19:15 393 查看
/*
* 静态方法引用:类名::静态方法名
*/
interface IMessage<P, R> {
public R transForm(P p);
}

public class Demo {
public static void main(String[] args) {
IMessage<Integer, String> im = String::valueOf;
System.out.println(im.transForm(1000));
System.out.println(im.transForm(9999).replaceAll("9", "8"));

}
}

/*
* 对象方法引用:实例对象::普通方法
*/
interface IMessage<R> {
public R upper();
}

public class Demo {
public static void main(String[] args) {
// 引用的是 public String toUpperCase();
IMessage<String> i = "Good"::toUpperCase;
System.out.println(i.upper());
}
}

/*
* 特定类型访法引用:特定类::普通方法
*/
interface IMessage<R> {
public int compare(R r1,R r2);
}

public class Demo {
public static void main(String[] args) {
// 引用的是 public int compareTo(String anotherString);
IMessage<String> i = String ::compareTo;
System.out.println(i.compare("A","B"));
}
}
/*
* 构造方法引用:类::new;
*/
interface IMessage<R> {
public R cread(String srt, 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) {
IMessage<Book>im=Book::new;
Book book=im.cread("Java", 79.6);
System.out.println(book);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  方法引用