Home > front end >  How to declare a variable that accepts method reference of any type Function<>
How to declare a variable that accepts method reference of any type Function<>

Time:09-17

I am trying to declare a variable that accepts method reference of any type Function<AnyObject, AnyObject or Any Enum>

This method reference would be used in mapper where I accept some inputs and map the respective value by calling the method referred to another object.

@Data // Lombok
public class ReferenceSample<T, R> {

  private final Function<T, R > methodReference; // should be able to accept any method reference

}

Following are the possible methods

     public class Common {

          public static String getMethod1(String a) {
            // Process
            return "result1";
          }

          public static SomeEnum getMethod2(String b) {
            // Process
            return SomeEnum.DATA;
          }
        }

When I try to create the object

new ReferenceSample(Common::getMethod1);

I get the following error

java: incompatible types: invalid method reference
    incompatible types: java.lang.Object cannot be converted to java.lang.String

CodePudding user response:

You needs to specialize the generic types as shown below.

public class Reference
{
    public static void main (String[] args)
    {
        Reference app = new Reference ();
        app.test ();
    }

    private void test ()
    {
        int[] row = {1, 1, 5, 2, 4};

        System.out.println ("Input: "   Arrays.toString (row));

        // This fails because the generic types have not been specified
        ReferenceSample rs1 = new ReferenceSample (Common::getMethod1);
        
        // This compiles but isn't specialized
        ReferenceSample<?, ?> rs2 = new ReferenceSample<> (Common::getMethod1);
        
        // This is preferred because it specifies the types precisely
        ReferenceSample<String, String> rs3 = new ReferenceSample<> (Common::getMethod1);
    }
}

class ReferenceSample<T, R>
{
    public Function<T, R> methodReference; // should be able to accept any method reference

    public ReferenceSample (Function<T, R> methodReference)
    {
        this.methodReference = methodReference;
    }
}

class Common
{
    public static String getMethod1 (String a)
    {
        // Process
        return "result1";
    }

    public static String getMethod2 (String b)
    {
        // Process
        return " "   b   " ";
    }
}
  • Related