Java 8新特性方法引用
对于引用来说我们一般都是用在对象,而对象引用的特点是:不同的引用对象可以操作同一块内容!
Java 8的方法引用定义了四种格式:
- 引用静态方法 ClassName :: staticMethodName
- 引用对象方法: Object:: methodName
- 引用特定类型方法: ClassName :: methodName
- 引用构造方法: ClassName :: new
静态方法引用示例
@FunctionalInterface interface FunStaticRef{ public R tranTest(P p); } public static void main(String[] args) { FunStaticRef
funStaticRef = String::valueOf; String str = funStaticRef.tranTest(10000); System.out.println(str.replaceAll("0", "9")); }
对象方法引用示例
@FunctionalInterface interface InstanRef{ public R upperCase(); } public static void main(String[] args) { String str2 = "i see you"; InstanRef instanRef = str2 :: toUpperCase; System.out.println(instanRef.upperCase()); }
特定类型方法引用示例
特定方法的引用较为难理解,本身其引用的是普通方法,但是引用的方式却为: ClassName :: methodName
@FunctionalInterface interface SpecificMethodRef{ public int compare(P p1 , P p2); } public static void main(String[] args) { SpecificMethodRef
specificMethodRef = String :: compareTo; System.out.println(specificMethodRef.compare("A","B")); ConstructorRef constructorRef = Book :: new; Book book = constructorRef.createObject("Java",100.25); System.out.println(book); }
构造方法引用示例
class Book{
private String title;
private double price;
public Book() {
}
public Book(String title,double price){
this.price = price;
this.title = title;
}
@Override
public String toString() {
return "Book{" +"title='" + title + ''' +", price=" + price +'}';
}
}
public static void main(String[] args) {
ConstructorRef constructorRef = Book :: new;
Book book = constructorRef.createObject("Java",100.25);
System.out.println(book);
}
总的来说Java 8一些新的特性在目前做的项目中还未大量使用,但是学习一下,到时也不至于看到这种Java 8新特性的代码而不知所错!
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!



