Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand constructor reference and method reference in Java

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

How to understand the constructor reference and method reference in Java, I believe that many inexperienced people are at a loss about this. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

JDK 8 witnessed the emergence of a special feature: constructor references and method references. Adrian D. Finlay explores how developers can unleash the real potential of constructor references.

Some background of method references

If you don't already know that the Java constructor itself is a special method, it will be helpful to read the basic examples of method references, by which you can understand what constructor references are.

A method reference provides a readable lambda expression for a method that already has a name. "

"they provide an easy way to reference methods without execution. "

The above is quoted from the official Java 8 programming reference tutorial (9th Edition), by Herbert Schildt

Method references can reference static methods and instance methods, both of which are common. Method references are instances of functional interfaces. Although Lambda expressions allow you to dynamically create method implementations, usually one method ends up calling another method in the Lambda expression to do what we want to do. A more direct approach is to use method references. This is useful when you already have a way to implement this functional interface.

Let's look at an example of using static methods and instance methods.

/ / step # 1-Create a funnctional interface.interface FuncInt {/ / contains one and only abstract methodString answer (String x, boolean y);} / / step # 2-Class providing method (s) that match FuncInt.answer () s definition.class Answer {static String ans_math_static (String x, Boolean y) {return "\" + x + "\" + "t =\ t" + y.toString (). ToUpperCase () } String ans_math_inst (String x, Boolean y) {return "\" + x + "\" + "\ t =\ t" + y.toString (). ToUpperCase ();}}

Translation note: the test case of the above code is as follows, because the result of the static method is the same as that of the instance method, only take the static method as an example.

Answer.ans_math_static ("9 > 11?", false); Answer.ans_math_static ("987.6

< 1.1 ?", false);Answer.ans_math_static("1 >

0. 9?, true); Answer.ans_math_static ("T Is Chengdu in Sichuan F: Does Dwyne Wade play for the Knicks?, true); Answer.ans_math_static ("-1% 0.2? 0? ", false); Answer.ans_math_static (" T hand F: Does Dwyne Wade play for the Knicks? ", false)

Get the same output as the original example:

"9 > 11?" = FALSE "987.6

< 1.1 ?" = FALSE"1 >

0. 9? "= TRUE" Tamp F: Is Chengdu in Sichuan? "= TRUE"-1% 0.2% 0? "= FALSE" TAccord F: Does Dwyne Wade play for the Knicks? "= FALSE

The main steps for using method references are:

1. Define a functional interface

two。 Define a method that meets the requirements of abstract methods for functional interfaces

3. Use the (x:: y) method defined in step 2 to reference an instance of the instantiated functional interface.

Translation note: the method reference format of static method is class name: method name; the method reference format of instance method is object instance name:: method name.

4. Call the method using a functional interface instance: Instance.AbstractMethod ()

This provides a pluggable way to create a method implementation. Lambda expressions and method references bring a functional boost to Java programming.

Method reference to the constructor

Let's start the discussion in detail.

A constructor is a method like any other method. Isn't that right? Wrong. They are a bit special. They are object initialization methods. Still, they are a method, and nothing can stop us from creating method references to constructors like other method references.

/ / step # 1-Create a funnctional interface.interface FuncInt {/ / contains one and only abstract methodAutomobile auto (String make, String model, short year);} / / step # 2-Class providing method (s) that match FuncInt.answer () s definition.class Automobile {/ / Trunk Member Variablesprivate String make;private String model;private short year;//Automobile Constructorpublic Automobile (String make, String model, short year) {this.make = make;this.model = model;this.year = year } protected void what () {System.out.println ("This Automobile is a" + year + "" + make + "+ model +".);}} / / Step # 3-Class making use of method referencepublic class ConstrRef {static void createInstance () {} public static void main (String [] args) {System.out.println (); / / Remember, a Method Reference is an instance of a Functional Interface. Therefore....FuncInt auto = Automobile::new;//We really don't gain much from this example//Example # 1Automobile honda = auto.auto ("honda", "Accord", (short) 2006); honda.what (); / / Example # 1Automobile bmw = auto.auto ("BMW", "530i", (short) 2006); bmw.what (); System.out.println ();}}

Output result

This Automobile is a2006 honda Accord.This Automobile is a2006 BMW 530i.

Description

The first thing users should know is that this basic example is not that practical. This is a rather circuitous way to create an object instance. In fact, you will almost certainly not go through all this hassle to create an instance of Automobile, but for the sake of conceptual integrity, mention it anyway.

The main steps for using the method reference of the constructor are:

1. Define a functional interface with only abstract methods that have the same return type as the object you intend to use for constructor reference.

two。 Create a class whose constructor matches the abstract method of the functional interface.

3. Instantiate an instance of a functional interface using a method reference to the constructor defined in step # 2.

Translation note: the method reference format of the constructor is class name:: new

4. In step # 2, use the constructor to reference an instance of the instantiated class, such as MyClass x = ConstructorReference.AbstractMethod (x, y, z...)

Constructor references become more useful when used with generics. By using the generic factory method, you can create various types of objects.

Let's have a look.

/ / step # 1-Create a funnctional interface.interface FuncInt {/ / contains one and only abstract methodOb func (X make, Y model, Z year);} / / step # 2-Create a Generic class providing a constructor compatible with FunInt.func ()'s definitionclass Automobile {/ / Automobile Member Variablesprivate X make;private Y model;private Z year;//Automobile Constructorpublic Automobile (X make, Y model, Z year) {this.make = make;this.model = model;this.year = year } protected void what () {System.out.println ("This Automobile is a" + year + "" + make + "" + model + ".);}} / / step # 3-Create a Non-Generic class providing a constructor compatible with FunInt.func ()'s definitionclass Plane {/ / Automobile Member Variablesprivate String make;private String model;private int year;//Plane Constructorpublic Plane (String make, String model, int year) {this.make = make;this.model = model;this.year = year / / Automatic unboxing} protected void what () {System.out.println ("This Plane is a" + year + "" + make + "+ model +".);}} / / Step # 3-Class making use of method reference with genericspublic class ConstrRefGen {/ / Here is where the magic happensstatic Ob factory (FuncInt obj, X p1, Y p2, Z p3) {return obj.func (p1, p2, p3);} public static void main (String [] args) {System.out.println () / / Example # 1FuncInt auto_cons = Automobile::new;Automobile honda = factory (auto_cons, "Honda", "Accord", 2006); honda.what (); / / Example # 2FuncInt plane_cons = Plane::new;Plane cessna = factory (plane_cons, "Cessna", "Skyhawk", 172); cessna.what (); System.out.println ();}}

Output result

This Automobile is a 2006 Honda Accord.This Plane is a 172 Cessna Skyhawk.

Description

There's a lot to digest here. In fact, if you've never studied generics in depth before, the code may look pretty obscure. Let's break it down.

The first thing we do is to create a generic functional interface. Attention to detail. We have four generic type parameters: Ob, X, Y, and Z.

Ob represents the class whose constructor you want to reference. Xjudicial Y Z represents the parameters of the constructor of this class.

If we replace the generic method placeholder, the abstract method might look like this: SomeClass func (String make, String model, int year). Note that because we make the interface generic, we can specify any return type or any class instance we want to return. This unleashes the real potential of constructor references.

The next two parts are relatively simple, and we create the same class, a generic class and a non-generic class to demonstrate their interoperability with the factory methods defined in the public class. Note that the constructors of these classes are compatible with the method signature of FuncInt.func ().

A file that enters a public class. This method is where miracles happen.

/ / Here is where the magic happensstatic Ob factory (FuncInt obj, X p1, Y p2, Z p3) {return obj.func (p1, p2, p3);}

We mark this method as static, so we don't have to use a ConstRefGen instance, which is, after all, a factory method. Note that the factory method has the same generic type parameters as the functional interface. Notice that the return type of the method is Ob, which can be any class we decide. Of course, X, Y, and Z are the method parameters of the method in Ob. Note that this function takes an instance of FuncInt as a parameter (class type and method parameters as type parameters), as well as a class of type Ob as a method parameter.

In the method body, it invokes the method reference and supplies it with the parameters passed in factory ().

Our first task is to create a method reference that conforms to FuncInt.

Here we refer to the constructors of the Automobile class and the Plane class, respectively.

Our next task is to create an object with a method reference.

To do this, we call factory () and provide it with the constructor reference it needs and the parameters about the constructor defined by factory (). Factory () has the flexibility to create constructor references to various methods because it is generic. Because the constructors of the Plane and Automobile classes match the method signatures of FuncInt.func (), they can be used as method references to FuncInt.func (). Factory () returns an instance of the class through a call to obj.func (XJY _ Z), which is a constructor method reference that, when evaluated, provides you with an instance of the class specified as its argument.

If you think about this problem for a while, you will find that it is a very useful supplement to Java.

After reading the above, have you learned how to understand constructor references and method references in Java? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report