Method References
Method references in Java provide a way to refer to methods or constructors without invoking them. They are often more concise and readable than lambda expressions, especially when the lambda expression merely calls an existing method. Method references are a shorthand notation of lambda expressions.
Static Method References:
Static method references refer to static methods using the syntax ClassName::staticMethodName
.
Example:
In the above example, System.out::println
is a static method reference to the println
method of the System
class.
Instance Method References:
Instance method references refer to instance methods of a particular object using the syntax object::instanceMethodName
.
Example:
In the above example, String::isEmpty
is an instance method reference for the isEmpty
method of the String
class.
Constructor References:
Constructor references create new objects using constructors. They follow the syntax ClassName::new
.
Example:
In the above example, Person::new
is a constructor reference that creates new Person
objects.
Method references enhance the readability of your code by allowing you to express instances where a lambda expression simply calls an existing method. They provide a clear and concise way to represent functional interfaces, making your code more expressive and easier to understand.
Last updated