每日一学--Java8 关键字::

关键字::

参考博客

用法

通过 :: 关键字来访问类的构造方法,对象方法,静态方法。

存在类something

class Something {
 
    // constructor methods
    Something() {}
 
    Something(String something) {
	System.out.println(something);
    }
 
    // static methods
    static String startsWith(String s) {
        return String.valueOf(s.charAt(0));
    }
    
    // object methods
    String endWith(String s) {
        return String.valueOf(s.charAt(s.length()-1));
    }
    
    void endWith() {}
}

定义接口(必须要用 functional interface 来接收,否则编译错误)

@FunctionalInterface
interface IConvert<F, T> { // 传参类型为F,返回类型为T
    T convert(F form);
}

@FunctionalInterface 注解要求接口有且只有一个抽象方法
访问静态方法:

// static methods
IConvert<String, String> convert = Something::startsWith;
String converted = convert.convert("123");

访问对象方法

// object methods
Something something = new Something();
IConvert<String, String> converter = something::endWith;
String converted = converter.convert("Java");

访问构造方法

// constructor methods
IConvert<String, Something> convert = Something::new;
Something something = convert.convert("constructors");

总结:
我们可以把类Something中的方法static String startsWith(String s){…}、String endWith(String s){…}、Something(String something){…}看作是接口IConvert的实现,因为它们都符合接口定义的那个“模版”,有传参类型F以及返回值类型T。
比如构造方法Something(String something),它传参为String类型,返回值类型为Something。注解@FunctionalInterface保证了接口有且仅有一个抽象方法,所以JDK能准确地匹配到相应方法。

复杂示例

把方法当做参数传入stream内部
旧式用法:

public class AcceptMethod {
 
    public static void  printValur(String str){
        System.out.println("print value : "+str);
    }
 
    public static void main(String[] args) {
        List<String> al = Arrays.asList("a","b","c","d");
        for (String a: al) {
            AcceptMethod.printValur(a);
        }
      //下面的for each循环和上面的循环是等价的 
        al.forEach(x->{
            AcceptMethod.printValur(x);
        });
    }
}

加入::

public class MyTest {
    public static void  printValur(String str){
        System.out.println("print value : "+str);
    }
 
    public static void main(String[] args) {
        List<String> al = Arrays.asList("a", "b", "c", "d");
        al.forEach(AcceptMethod::printValur);
        //下面的方法和上面等价的
        Consumer<String> methodParam = AcceptMethod::printValur; //方法参数
        al.forEach(x -> methodParam.accept(x));//方法执行accept
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值