Java 8新特性方法引用
对于引用来说我们一般都是用在对象,而对象引用的特点是:不同的引用对象可以操作同一块内容!
Java 8的方法引用定义了四种格式:
- 引用静态方法 ClassName :: staticMethodName
- 引用对象方法: Object:: methodName
- 引用特定类型方法: ClassName :: methodName
- 引用构造方法: ClassName :: new
静态方法引用示例
/** * 静态方法引用 * @param <P> 引用方法的参数类型 * @param <R> 引用方法的返回类型 */@FunctionalInterfaceinterface FunStaticRef<P,R>{
public R tranTest(P p);
}
public static void main(String[] args) {
/* * 静态方法引用: public static String valueOf * 即将String的valueOf() 方法引用为 FunStaticRef#tranTest 方法 */ FunStaticRef<Integer, String> funStaticRef = String::valueOf;
String str = funStaticRef.tranTest(10000);
System.out.println(str.replaceAll("0", "9"));
}
对象方法引用示例
/** * 普通方法引用 * @param <R> 引用方法返回类型 */@FunctionalInterfaceinterface InstanRef<R>{
public R upperCase();
}
public static void main(String[] args) {
/* * 普通方法的引用: public String toUpperCase() * */ String str2 = "i see you";
InstanRef<String> instanRef = str2 :: toUpperCase;
System.out.println(instanRef.upperCase());
}
特定类型方法引用示例
特定方法的引用较为难理解,本身其引用的是普通方法,但是引用的方式却为: ClassName :: methodName
/** * 特定方法的引用 * @param <P> */@FunctionalInterfaceinterface SpecificMethodRef<P>{
public int compare(P p1 , P p2);
}
public static void main(String[] args) {
/* * 特定方法的引用 public int compareTo(String anotherString) * 与之前相比,方法引用前不再需要定义对象,而是可以理解为将对象定义在了参数上! */ SpecificMethodRef<String> specificMethodRef = String :: compareTo;
System.out.println(specificMethodRef.compare("A","B"));
ConstructorRef<Book> 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<Book> constructorRef = Book :: new;
Book book = constructorRef.createObject("Java",100.25);
System.out.println(book);
}
总的来说Java 8一些新的特性在目前做的项目中还未大量使用,但是学习一下,到时也不至于看到这种Java 8新特性的代码而不知所错!
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!