Java8新特性之三方法引用

来源:互联网 发布:linux 移植mt7688 编辑:程序博客网 时间:2024/05/21 17:12
package com.guigu.java8;


/**
 * Java8新特性:方法引用 (在Java8中要如果使用关于Java8中对于接口新增加的功能,必须要求一个接口只能定义一个抽象方法)
 *  方法引用在Java8之中一共定义了四种形式
 *    1) 引用静态方法:  类名称 ::static 方法名称;
 *    2) 引用某个对象的方法: 实例化对象 :: 普通方法;
 *    3) 引用特定类型的方法: 特定类 :: 普通方法;
 *    4) 引用构造方法: 类名称 :: new;
 * @author pqd
 *  P:引用方法的参数类型
 *  R:引用方法的返回值类型
 */
/*
 * 实现方法的引用接口
 */
//在java8中使用"函数式注解"在接口上声明,显示表示此接口只能定义一个抽象方法
@FunctionalInterface
interface Imessage2<P,R>{
public R zhuanhuan(P p);
}
interface Imessage3<R>{
public R upper();
}
@FunctionalInterface  //此接口为函数式接口,在接口中只能定义一个抽象方法
interface Imessage4<P>{
public int compare(P p1,P p2);
}
@FunctionalInterface  //此接口为函数式接口,在接口中只能定义一个抽象方法
interface Imessage5<C>{
public C create(String t,double p);
}
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 MethodDemo {
public static void main(String[] args) {
//范例一:引用静态方法
  //:在String类里面有一个valueOf()方法:public static String valueOf(int index);
//将String.valueOf()方法变为了Imessage2接口里面的zhuanhuan(P p)方法
Imessage2<Integer,String> msg=String::valueOf;
String str=msg.zhuanhuan(100);
System.out.println("valueOf方法[将Integer类型转化为String类型]: "+str);
    System.out.println(str.replaceAll("0", "9"));
    //范例二:引用某个对象的方法
    // :在String类里面有一个toUpperCase()方法:public String toUpperCase();
      //将String类的toUpperCase变为了Imessage3接口里面的upper()方法
    Imessage3<String> msg1="hello"::toUpperCase;
String str1=msg1.upper();
System.out.println("toUpperCase方法[将字符串的所有字母转化为大写]: "+str1);
  //范例三:引用特定类型的方法:
Imessage4<String> msg2=String::compareTo;
int result=msg2.compare("Java", "Java8");
System.out.println(result);
  //范例四:引用构造方法
Imessage5<Book> msg3=Book::new;
Book book=msg3.create("Java8新特性之方法引用",30.8);
System.out.println(book);
}
}
原创粉丝点击