Jdk1.8新特性 - 方法引用

一、说明

方法引用使用一对冒号 :: 标识;通过方法的名字来指向一个方法;是函数式接口的另一种书写方式

通过方法引用,可以将方法的引用赋值给一个Function变量;Lambda表达式一般用于自己提供方法体,而方法引用一般直接引用现成的方法

二、示例

  •     1、静态方法引用
	/**
	 * 方法无参,有返回
	 */
	Supplier<Double> supplierD = Math::random;
	
	System.out.println(supplierD.get());
	
	/**
	 * 方法单参,有返回
	 */
	Function<String, Integer> fun = Integer::parseInt;
	Integer value = fun.apply("123");
	
	System.out.println(value);
  •     2、动态方法引用
	/**
	 *  方法无参,有返回
	 */
	Supplier<String> supplierS = str::toUpperCase;
	
	System.out.println(supplierS.get());
	
	/**
	 *  方法单参,有返回
	 */
	Function<Integer, String> functionS = str::substring;
	
	System.out.println(functionS.apply(2));
	
	/**
	 *  方法单参,无返回
	 */
	Person p = new Person();
	Consumer<String> consumerP = p::setName;
	consumerP.accept("张三");
	
	System.out.println(p);
  •     3、构造方法引用
	/**
	 *  方法无参
	 */
	Supplier<Person> supplierP = Person::new;
	
	System.out.println(supplierP.get());
	
	/**
	 *  方法二参
	 */
	BiFunction<Integer, String, Person> bifunctionP = Person::new;
	
	System.out.println(bifunctionP.apply(1, "张三"));
	
	/**
	 *  方法三参 (Jdk没有内置支持该模式的函数式接口,需要自定义,见附录)
	 */
	CustomFunction<Integer, String, String, Person> customFunctionP = Person::new;
	
	System.out.println(customFunctionP.apply(1, "张三", "广州"));

三、附录

  •     1、Person 定义
public class Person {
	
	private Integer id;
	private String name;
	private String address;
	

	public Person() {
		
	}

	public Person(Integer id) {
		super();
		this.id = id;
	}

	public Person(Integer id, String name) {
		super();
		this.id = id;
		this.name = name;
	}

	public Person(Integer id, String name, String address) {
		super();
		this.id = id;
		this.name = name;
		this.address = address;
	}

    getter / setter ...

    toString ...

}
  •     2、自定义函数式接口
/**
 * 泛型接口:接收 三个类型的参数,返回另一个类型的结果
 */
public interface CustomFunction<T,B,A,R> {
	
	R apply(T t, B b, A a);
	
}

/**
 * 指定类型接口: 接收 用户、商品、地址,返回订单
 */
public interface CustomFunction {

	Order apply(User user, Goods goods, Address address);

}

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值