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
.
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;
Yes, you can using the UnaryOperator.identity()
as:
UnaryOperator<Object> defaultParser = UnaryOperator.identity();
which is defined with a lambda expression as
static <T> UnaryOperator<T> identity() {
return t -> t;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.