JDK8新特性-方法引用

1. 概念


  • 方法引用就是给一个方法设置别名,相当于一个方法定义了不同的名字。

  • 方法引用在Java8中共定义了4中形式

    • 引用静态方法: 类名称::static方法名称
    • 引用某个对象的方法: 实例化对象::普通方法
    • 引用特定类的方法: 特定类::方法
    • 引用构造方法: 类名称::new

2. 引用静态方法


  • 在String类中有valueOf()方法
/**
 * 实现方法的引用接口
 * @param <P> 引用方法的参数类型
 * @param <R> 引用方法的返回值类型
 */
@FunctionalInterface
interface IMessage3<P, R> {
    R zhuanhuan(P p);
}

public class MethodReferenceDemo1 {
    public static void main(String... args) {
        // 将String.valueOf()方法变为了IMessage接口里的zhuanhuan()方法
        IMessage3<Integer, String> msg = String :: valueOf;
        String str = msg.zhuanhuan(1000);
        System.out.println(str.replaceAll("0", "9"));
    }
}

3. 普通方法引用


/**
 * 实现方法的引用接口
 * @param <R> 引用方法的返回值类型
 */
@FunctionalInterface
interface IMessage3<R> {
    R upper();
}

public class MethodReferenceDemo1 {
    public static void main(String... args) {
        IMessage3<String> msg = "hello" :: toUpperCase;
        String str = msg.upper();
        System.out.println(str);
    }
}

4. 特定类对象引用


  • 需要特定类的对象支持
  • String类中的compareTo
@FunctionalInterface
interface IMessage3<P> {
    int compare(P p1, P p2);
}

public class MethodReferenceDemo1 {
    public static void main(String... args) {
        IMessage3<String> msg = String :: compareTo;
        System.out.println(msg.compare("A", "B"));
    }
}
  • 与此前相比,方法引用前不需要定义对象,而是可以理解为将对象定义在了参数上

5. 引用构造方法


@FunctionalInterface
interface IMessage3<C> {
    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 MethodReferenceDemo1 {
    public static void main(String... args) {
        IMessage3<Book> msg = Book :: new; // 引用构造方法
        Book book = msg.create("Java开发", 20.22);
        System.out.println(book.toString());
    }
}

转载于:https://my.oschina.net/shadowolf/blog/2994534

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值