Что такое метод референс java
Перейти к содержимому

Что такое метод референс java

  • автор:

Method References

You use lambda expressions to create anonymous methods. Sometimes, however, a lambda expression does nothing but call an existing method. In those cases, it’s often clearer to refer to the existing method by name. Method references enable you to do this; they are compact, easy-to-read lambda expressions for methods that already have a name.

Consider again the Person class discussed in the section Lambda Expressions:

Suppose that the members of your social networking application are contained in an array, and you want to sort the array by age. You could use the following code (find the code excerpts described in this section in the example MethodReferencesTest ):

The method signature of this invocation of sort is the following:

Notice that the interface Comparator is a functional interface. Therefore, you could use a lambda expression instead of defining and then creating a new instance of a class that implements Comparator :

However, this method to compare the birth dates of two Person instances already exists as Person.compareByAge . You can invoke this method instead in the body of the lambda expression:

Because this lambda expression invokes an existing method, you can use a method reference instead of a lambda expression:

The method reference Person::compareByAge is semantically the same as the lambda expression (a, b) -> Person.compareByAge(a, b) . Each has the following characteristics:

  • Its formal parameter list is copied from Comparator<Person>.compare , which is (Person, Person) .
  • Its body calls the method Person.compareByAge .

Kinds of Method References

There are four kinds of method references:

Kind Syntax Examples
Reference to a static method ContainingClass::staticMethodName Person::compareByAge
MethodReferencesExamples::appendStrings
Reference to an instance method of a particular object containingObject::instanceMethodName myComparisonProvider::compareByName
myApp::appendStrings2
Reference to an instance method of an arbitrary object of a particular type ContainingType::methodName String::compareToIgnoreCase
String::concat
Reference to a constructor ClassName::new HashSet::new

The following example, MethodReferencesExamples , contains examples of the first three types of method references:

All the System.out.println() statements print the same thing: Hello World!

BiFunction is one of many functional interfaces in the java.util.function package. The BiFunction functional interface can represent a lambda expression or method reference that accepts two arguments and produces a result.

Reference to a Static Method

The method references Person::compareByAge and MethodReferencesExamples::appendStrings are references to a static method.

Reference to an Instance Method of a Particular Object

The following is an example of a reference to an instance method of a particular object:

The method reference myComparisonProvider::compareByName invokes the method compareByName that is part of the object myComparisonProvider . The JRE infers the method type arguments, which in this case are (Person, Person) .

Similarly, the method reference myApp::appendStrings2 invokes the method appendStrings2 that is part of the object myApp . The JRE infers the method type arguments, which in this case are (String, String) .

Reference to an Instance Method of an Arbitrary Object of a Particular Type

The following is an example of a reference to an instance method of an arbitrary object of a particular type:

The equivalent lambda expression for the method reference String::compareToIgnoreCase would have the formal parameter list (String a, String b) , where a and b are arbitrary names used to better describe this example. The method reference would invoke the method a.compareToIgnoreCase(b) .

Similarly, the method reference String::concat would invoke the method a.concat(b) .

Reference to a Constructor

You can reference a constructor in the same way as a static method by using the name new . The following method copies elements from one collection to another:

The functional interface Supplier contains one method get that takes no arguments and returns an object. Consequently, you can invoke the method transferElements with a lambda expression as follows:

You can use a constructor reference in place of the lambda expression as follows:

The Java compiler infers that you want to create a HashSet collection that contains elements of type Person . Alternatively, you can specify this as follows:

Java 8 Method References explained in 5 minutes

At IDR Solutions we use Java 8 for the development of our products (a Java PDF Viewer and SDK, PDF to HTML5 converter and a Java ImageIO replacement). As I spend a lot of time using Java 8 I thought that it might be useful to a series article of the new features in JDK8.

In this article, we will be looking at Method References.

What are Method References?

It is a feature that is related to Lambda Expression. It allows us to reference constructors or methods without executing them. Method references and Lambda are similar in that they both require a target type that consists of a compatible functional interface.

Types of Method Reference

There are four types of method reference, the table below summarizes this.

Type Example Syntax
1. Reference to a static method ContainingClass::staticMethodName Class::staticMethodName
2. Reference to a constructor ClassName::new ClassName::new
3. Reference to an instance method of an arbitrary object of a particular type ContainingType::methodName Class::instanceMethodName
4. Reference to an instance method of a particular object containingObject::instanceMethodName object::instanceMethodName

I will explain further the four types of methods referenced in the table.

1 . Reference to a Static Method

As you can see in this code, we made reference to a static method in this class.

Containing class ReferenceToStaticMethod
staticMethodName isPrime

As I mentioned above, the Method reference is very similar to Lambda. Let’s look at the difference here

Lambda Form List primeNumbers = ReferenceToStaticMethod.testPredicate(numbers, a -> ReferenceToStaticMethod.isPrime(a));
Method Reference List primeNumbers = ReferenceToStaticMethod.testPredicate(numbers, ReferenceToStaticMethod::isPrime);

2. Reference To Constructor

This mean providing reference to any of the persons object in the List of a particular type which is the Person .So the containing type is persons and the method name is getAge();

ContainingType Person
methodName getAge
Lambda Form List allAges = ReferenceToInstanceMethodAOPT.listAllAges(persons, x -> x.getAge());
Method Reference List allAges = ReferenceToInstanceMethodAOPT.listAllAges(persons, Person::getAge);

4. Reference To An Instance Method Of A Particular Object

Since System.out is an instance of type PrintStream , we then call the println method of the instance.

containingObject System.out
instanceMethodName println
Lambda Form ReferenceToInstanceMethodOAPO.printNames(names, x -> System.out.println(x));
Method Reference ReferenceToInstanceMethodOAPO.printNames(names,System.out::println);

So what can we Take Away?

  1. You can use replace Lambda Expressions with Method References where Lamdba is invoking already defined methods.
  2. You can’t pass arguments to methods Reference
  3. To use Lambda and Method Reference, make sure you have Java 8 installed. They do not work on Java 7 and earlier versions.

If you found this article useful, you may also be interested in our other Java8 posts on Lambda Expression, Streams API, Default Methods, Consumer Suppliers, Optional and Repeating Annotations.

We also now have a large collection of articles on what is new in other versions of Java, including Java9, Java12 and OpenJDK.

Are you a Developer working with PDF files?

Our developers guide contains a large number of technical posts to help you understand the PDF file Format.

Популярно о лямбда-выражениях в Java. С примерами и задачами. Часть 2

Передаем ссылку на статический метод ИмяКласса:: имяСтатическогоМетода?

Передаем ссылку на не статический метод используя существующий объект имяПеременнойСОбъектом:: имяМетода

Передаем ссылку на не статический метод используя класс, в котором реализован такой метод ИмяКласса:: имяМетода

Передаем ссылку на конструктор ИмяКласса::new
Использование ссылок на методы очень удобно, когда есть готовый метод , который вас полностью устраивает, и вы бы хотели использовать его в качестве callback-а. В таком случае, вместо того чтобы писать лямбда-выражение с кодом того метода, или же лямбда-выражение, где мы просто вызываем этот метод, мы просто передаем ссылку на него. И всё.

Что такое метод референс java

Functional Interfaces in Java and Lambda Function are prerequisites required in order to grasp grip over method references in Java. As we all know that a method is a collection of statements that perform some specific task and return the result to the caller. A method can perform some specific task without returning anything. Methods allow us to reuse the code without retyping the code. In this article, we will see how to use methods as value.

In Java 8 we can use the method as if they were objects or primitive values, and we can treat them as a variable. The example shows the function as a variable in java:

Sometimes, a lambda expression only calls an existing method. In those cases, it looks clear to refer to the existing method by name. The method references can do this, they are compact, easy-to-read as compared to lambda expressions. A method reference is the shorthand syntax for a lambda expression that contains just one method call. Here’s the general syntax of a

Generic syntax: Method reference

A. To refer to a method in an object

B. To print all elements in a list

Following is an illustration of a lambda expression that just calls a single method in its entire execution:

C. Shorthand to print all elements in a list

To make the code clear and compact, In the above example, one can turn lambda expression into a method reference:

The method references can only be used to replace a single method of the lambda expression. A code is more clear and short if one uses a lambda expression rather than using an anonymous class and one can use method reference rather than using a single function lambda expression to achieve the same. In general, one doesn’t have to pass arguments to method references.

The following example is about performing some operations on elements in the list and adding them. The operation to be performed on elements is a function argument and the caller can pass accordingly.

Illustration:

Following are the ways to call the above method as depicted below as follows:

Types of Method References

There are four type method references that are as follows:

  1. Static Method Reference.
  2. Instance Method Reference of a particular object.
  3. Instance Method Reference of an arbitrary object of a particular type.
  4. Constructor Reference.

To look into all these types we will consider a common example of sorting with a comparator which is as follows:

Type 1: Reference to a static method

If a Lambda expression is like:

// If a lambda expression just call a static method of a class
(args) -> Class.staticMethod(args)

Then method reference is like:

// Shorthand if a lambda expression just call a static method of a class
Class::staticMethod

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *