Java新特性——方法引用(::的使用方法)

上一次介绍了Java8新特性中的Lambda表达式,现在继续讲解Java8的新特性之二:
方法引用:方法引用其实也离不开Lambda表达式。

方法引用的类型

类型对应Lambda表达式语法
静态方法引用(args) -> 类名.static_Method(args)类名::staticMethod
对象方法引用(inst,args) -> 类名.inst_Method(args)类名::instMethod
实例方法引用(args) -> inst.inst_Method(args)inst::instMethod
构建方法引用(args) -> new 类名(args)类名::new

方法引用举例

/**
 * JDK8新特性之方法引用
 */
public class Demo6 {
    //类型 	        语法 	                对应lambda表达式
    //构造器引用 	Class::new 	            (args) -> new 类名(args)
    //静态方法引用 	Class::static_method 	(args) -> 类名.static_method(args)
    //对象方法引用 	Class::method 	        (inst,args) -> 类名.method(args)
    //实例方法引用 	instance::method 	    (args) -> instance.method(args)


    /**
     *对象方法引用
     * 对象::method
     */
    @Test
    public void test01(){
        List<String> wordsList = GetListData.wordsList;
		//上一章提到的
        //wordsList.forEach(s-> System.out.println(s));
        //wordsList.forEach(System.out::println);

        Date date = new Date();
        /*long time = date.getTime();
        System.out.println(time);*/
        //返回一个毫秒数的时间戳  1970-现在的毫秒数
        //进行对象方法引用之后
        Supplier<Long> getTime = date::getTime;
        Long aLong = getTime.get();
        System.out.println(aLong);
    }

    /**
     * 类名::静态方法
     */
    @Test
    public void test02(){
        Supplier<Long> currentTimeMillis = System::currentTimeMillis;
        System.out.println(currentTimeMillis.get());
    }

    /**
     * 类名::实例方法
     */
    @Test
    public void test03(){
        //
        Function<String,Integer> length = String::length;
        System.out.println(length.apply("helloworld"));
    }

    @Test
    public void test04(){
        Supplier<Student> student = Student::new;
        Student student1 = student.get();
        student1.setName("ange");
        student1.setAge(18);
        System.out.println(student1);

    }

}

嗯,还是这么简单,依旧是将代码简化
继续装逼

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值