Java—新特性(方法引用)

1.方法引用
方法引用的类型有四种形式:
(1)引用静态方法:类名称::static 方法名称 ;
(2)引用某个对象的方法:实例化对象 :: 普通方法 ;
(3)引用某个特定类的方法: 类名称 :: 普通方法 ;
(4)引用构造方法: 类名称 :: new 。

1.1引用静态方法
就相当于为方法起了个别名
package www.bit.java.testdemo;
@FunctionalInterface
// 是一个函数式编程接口,只允许有一个方法
//函数泛型接口
interface IUtil<P,R> {
public R switchPara(P p) ;
}
public class TestDemo {
public static void main(String[] args) {
//进行方法引用
// String valueOf类的静态方法
IUtil<Integer,String> iu = String :: valueOf ;

    // 相当于调用了String.valueOf(1000) 
    String str = iu.switchPara(1000) ; 
    System.out.println(str.length());
}

}

1.2引用对象方法 y=f()
String中的toUpperCase()方法为对象方法
package www.bit.java.testdemo;
@FunctionalInterface // 是一个函数式编程接口,只允许有一个方法
interface IUtil {
public R switchPara() ;
}

public class TestDemo {
public static void main(String[] args) {
IUtil iu = “hello” :: toUpperCase ; // 进行方法引用
System.out.println(iu.switchPara()); // 转换的就是这个"hello"
}
}

1.3引用类中普通方法
类名::成员方法
String有一个compareTo成员方法,此方法为普通方法
package www.bit.java.testdemo;
@FunctionalInterface
// 是一个函数式编程接口,只允许有一个方法
interface IUtil<R,P> {
public R compare(P p1,P p2) ;
}
public class TestDemo {
public static void main(String[] args) {
IUtil<Integer,String> iu = String :: compareTo ;
System.out.println(iu.compare(“刘”, “霍”));
}
}

1.4 引用构造方法
类(x)–>函数接口(x)
package www.bit.java.testdemo;
class Person {
private String name ;
private int age ;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return “Person [name=” + name + “, age=” + age + “]”;
}
}

@FunctionalInterface // 是一个函数式编程接口,只允许有一个方法
interface IUtil<R,PN,PA> {
public R createPerson(PN p1,PA p2) ;
}
public class TestDemo {
public static void main(String[] args) {
IUtil<Person,String,Integer> iu = Person :: new;
// 相当于调用Person类的构造方法
System.out.println(iu.createPerson(“yuisama”, 25));
}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值