"Method Reference" for Android using JAVA8 new feature

Source: Internet
Author: User

Objective

Previous: Android uses Java8 new feature lambda expression (with the command-mode simplification)
Said lambda expression, environment configuration and application in Android Studio. This paper describes the "method reference" of the new Java8 feature.
"Method Reference", which can actually be seen as a shorthand form of a lambda expression.
Look again at the scenario where lambda expressions are used: simplifying calls with only a single abstract method interface

4 Types of method references

The symbolic form of a method reference, such as a shape,
[ClassName | class-instance]::[static-method | instance-method | construct-method]
That is, prefix the class name or instance object of the class with two colons (::) connection, followed by a static method or an instance method, or a constructor method

Classification:
1. Static method references
2. Instance method references
3. Class instance method reference
4. Construction Method Reference

static method Reference

There is a static method under class Methodreferenceactivity:

staticintstr) {//被lambda表达式或"方法引用"调用   return Integer.parseInt(str);}

If you call methodreferenceactivity directly::p Arz is of course not, because "method reference" is used to replace a lambda expression, so it will also refer to an interface that contains only a single abstract method .

There is one more interface:

publicinterface ToIntFunc<T> {//注:原生jdk中就有的方法,安卓中没有    intvalue);}

There is another static method that uses the Tointfunc interface:

publicstaticintparse(ToIntFunc<String> f, String num) {   return f.applyAsInt(num);}

Use a lambda expression when you call Parse ():

int parseValue = parse((value -> parz(value)), num);

Use "method Reference" when calling Parse ():

int parseValue = parse(MethodReferenceActivity::parz, num);
Instance method reference

Remove the static from the above method in the parse method declaration:

publicintparse(ToIntFunc<String> f, String num) {   return f.applyAsInt(num);}

Use "method Reference" when calling Parse ():

int parseValue = parse(this//this指当前类的实例对象
The class instance method reference needs to be called externally in the method, declaring the parameter

If there is an inner class person:

StaticClass Person { Public  Person() {    } Public  Person(String name) { This. name = name;    } String name; Long birthday; PublicLongGetbirthday() {returnBirthday } PublicStringGetName() {returnName } Public Boolean Comparebyname(Person B) {intresult = This. Name.comparetoignorecase (B.name);if(Result = =1) {return true; }Else{return false; }    }@Override     PublicStringtoString() {return "person{"+"Name= '"+ name +' \ '+", birthday="+ Birthday +'} '; } Public void Printinfo() {System.out.println () (toString ()); }}

There is an interface compare:

publicinterface Compare<T> {    boolean compareTo(T v1, T v2);}

The external use of interface Compare calls method IsLarge:

publicbooleanisLarge(Compare<Person> c, Person p1, Person p2) {    return c.compareTo(p1, p2);}

Using lambda expressions and class instance method references:

person p1 = new  person ( "stone" ); person P2 = new  person ( "Sun" ); Boolean result = Islarge ((v1, v2), V1.comparebyname (v2), p1, p2) ; Span class= "Hljs-title" >system . out . println   ( "P1 sort after P2:"  + result) ; result  = islarge   ( Person::comparebyname, p1, p2) ; system . out . println   ( "P1 sort after P2:"  + result) ;   

Here the IsLarge method, in addition to the interface, requires that an instance object of two person be passed. These two objects are used by the CompareTo method in the Compare interface.

You do not need to call the method externally, declare the parameter

Let's look at the following set of code:

Integer[] ary = {2815634};Arrays.sort(ary, (o1, o2) -> o1.compareTo(o2));Arrays.sort(ary, Integer::compareTo);

This is called the Array Tool class Arrays.sort () to sort.
In "Arrays.sort (ary, Integer::compareto);", "class instance method reference" actually refers to the Java.util.Comparator interface, the static method in the interface is: int compare (t O1, T O2) O1, O2 parameters are not passed here. The instantiation of the O1,o2 is actually done inside the sort method. Like the example below,

/**内部实例化*/publicbooleanisLarge(Compare<Person> c) {    new Person("stone");    new Person("austin");    return c.compareTo(p1, p2);}

Using Lambda and class instance method references:

isLarge((v1, v2) -> v1.compareByName(v2));//lambda expressionisLarge(Person::compareByName);//method reference
Constructing method references

The following code is available:

StaticClass Person {String name; Public  Person() {    } Public  Person(String name) { This. name = name; }} Public Interfacegettype<t> {TGet(Stringvalue);} Public Interfacegettype2<t> {TGet();} PublicPersonGetperson(String name, gettype<person> data) {returnData.Get(name);} PublicPersonGetperson(gettype2<person> data) {returnData.Get();}

Using lambda and construction method references:

getPerson("li si", value ->new Person(value));//lambda//会调用new Person(String name)     指代GetTypegetPerson("zhang san"Person::new);getPerson(() -> new Person());//lambdagetPerson(Person::new);//会调用new Person()   指代GetType2
Summarize

Either lambda expressions or "method references," they all refer to an anonymous inner class instance that contains only a single abstract method interface. When you use a method reference, you can guess the category that the method refers to by looking at the expression. In conjunction with AS, look at the interface of the calling method.
The return value of the method reference expression is consistent with the return value of the method in the interface. The parameters of the method called by the method reference expression, which can be passed externally by calling the method. If there are arguments, and no value is passed, it may have been initialized inside the external method, such as the second example of class instance method reference.

A lambda expression can have a method body. Now that you have a "method reference," You don't have to look so "chaotic". Like what:

button.setOnTouchListener((view, event)-> {    if (event.getAction() == MotionEvent.ACTION_DOWN) {        //do sth.        return true;    } else if (event.getAction() == MotionEvent.ACTION_MOVE) {        //do sth.        return true;    }    return super.onTouchEvent(event);});

You only need to declare a method:

privatehandleEventevent) {    //do sth.    returntrue;}

Use the "method reference" call as follows:

button.setOnTouchListener(this::handleEvent);

"Method Reference" for Android using JAVA8 new feature

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.