役に立ちましたか?

質問

Reference to a constructor using method references in Java8

Java8Object Oriented ProgrammingProgramming

Lambda expressions In Java allows you to pass functionality as an argument to a method. You can also call an existing method using lambda expressions.

list.forEach(n -> System.out.println(n));

Method references are simple, easy-to-read lambda expressions to call/refer and the existing method by name in a lambda expression. In addition to the instance and static methods, you can also refer a constructor by using the new keyword.

Syntax

Following is the syntax to reference a constructor in Java.

ClassName::new

Example

interface myInterface{
   Test greet(String data);
}
class Test{
   Test(String data){
         System.out.println(data);
   }
}
public class MethodReferences {
   public static void main(String args[]) {
      myInterface in = Test::new;
      in.greet("Welcome to Tutorilspoint");
   }
}

Output

Welcome to Tutorilspoint
raja
Published on 08-Apr-2020 16:54:20
Advertisements
役に立ちましたか?
所属していません Tutorialspoint
scroll top