Thursday 7 May 2015

Java 8- Method and Constructor References

Method Referencing

Method reference is feature related to lambda expressions. Method references are more readable

form of Lambda expressions for already written methods. “::” operator is used to define method

reference. It provides a way to a method without executing it. In order to that a method

reference requires a target type context that consists of a compatible functional interface.

Method reference when evaluated creates an instance of the functional interface. The 2 types

of method references are:-

a). Static Method References.

    Syntax:-  ClassName :: methodName

Ex:-

    public interface Parent
    {
            String process(String input);
    }
    public class MethodReference
    {
            public static String toUpperStatic(String input)
            {
                    return input.toUpperCase();
             }
          public static void main(String... args)
            {
                 Parent parent = Parent::toUpperStatic;
         System.out.println("Static reference = "+parent .process("static"));
                 }
    }

b). Instance Method References Of Objects.

    Syntax:-   objRef :: methodName

Ex:-

    public interface Parent
        {
                String process(String input);
        }
        public class MethodReference
        {
                public String toUpperInstance(String input)
                {
                        return input.toUpperCase();
               }
              public static void main(String... args)
                {
                    MethodReference methodReference = new MethodReference();
                         Parent parent  = methodReference::toUpperInstance;
                 System.out.println("Instance reference  "+parent .process("instance"));
                     }
        }

Constructor Referencing

you can create references to the constructors. In Constructor references the method name is

"new" and the receiver is always the name of the class that is defining the constructor. You

can assign a constructor reference to any functional interface which has a method compatible

with the constructor.

    Syntax:-    ClassName :: new

Ex:-

    package com.evon;
        @FunctionalInterface
        public interface MyString
        {
                String strFunc(char[] chArray);
        }
        public class StringCreator
        {
              public static void main(String[] args)
            {
                        MyString mystr = String::new;
                        char[] charArray =

{'e','v','o','n','t','e','c','h','n','o','l','o','g','y'};
                        System.out.println(mystr.strFunc(charArray));
            }
        }

In above example we have assigned a String constructor reference to the functional interface

which we have created just now.

Hope this will help you :)

you can find such more blogs on http://findnerd.com/NerdDigest

No comments:

Post a Comment