Search code examples
javajava-8method-referencefunctional-interfaceunary-operator

How can I use reference method in a UnaryOperator java 8


Currently, I have a UnaryOperator like this

UnaryOperator<Object> defaultParser = obj -> obj;

I don't know if I can use a method reference in these kinds of operation. Example:

UnaryOperator<String> defaultParser = String::toString;

But with the generic way, not just String.


Solution

  • If you just want to avoid the lambda expression, UnaryOperator has static identity() method:

    UnaryOperator<Object> defaultParser = UnaryOperator.identity();
    

    If you specifically want a method reference (why??), you can define a method in your class

    public static <T> T identity(T t) {
        return t;
    }
    

    Then you will be able to use it as a method reference:

    UnaryOperator<Object> defaultParser = MyClass::identity;