当前位置: 移动技术网 > IT编程>开发语言>Java > Java 8新特性方法引用详细介绍

Java 8新特性方法引用详细介绍

2019年07月22日  | 移动技术网IT编程  | 我要评论

我的战神女奴,三人行网络班级,韵达快递单号

java 8新特性方法引用

 对于引用来说我们一般都是用在对象,而对象引用的特点是:不同的引用对象可以操作同一块内容!

  java 8的方法引用定义了四种格式:

  1. 引用静态方法     classname :: staticmethodname
  2. 引用对象方法:  object:: methodname
  3. 引用特定类型方法: classname :: methodname
  4. 引用构造方法: classname  :: new

 静态方法引用示例

/**
 *   静态方法引用
 * @param <p> 引用方法的参数类型
 * @param <r> 引用方法的返回类型
 */
@functionalinterface
interface 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> 引用方法返回类型
 */
@functionalinterface
interface 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>
 */
@functionalinterface
interface 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新特性的代码而不知所错!

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网