Java 8: get operator-object-object with a reference to a method

I wondered if it was possible in Java 8 to get references to the methods of standard operators (+, -, <,>, ...).

I want to get it as Foo::+ , where Foo is a certain place where I can get it. Since Java does not allow special characters in method names, I don’t think this is possible?

If the path above does not exist: is there some place where the standard operators are defined as Foo::plus ?

I know that it is possible to define it as a lambda ( (x, y) -> x + y ), but, in my opinion, it can be more expressive in some cases with a reference to a method, as is possible in Haskell.

+8
java lambda java-8 method-reference
source share
3 answers

I believe that you are looking for int Integer.sum(int, int) and similar methods that are actually provided by the API.

There are many methods from your list, but for JDK this does not mean that it does not provide the last inch of convenience, because its size is huge even without them.

If this is a consolation, each of my projects has a Util class where I will give duplicates such as these.

+7
source share

A clean way would be the Operators helper class, which contains methods for all operators. Then you can use these methods as references. Of course, a standard library class would be better than its own helper class, but at least you can define the name of this helper class so that you can choose the name that expresses you most.

+1
source share

Standard operators apply only to boxed primitives and primitives, and you cannot dynamically find which operators apply to the object in question.

Edit: if you want to know which method you could call to perform standard operator functions, you can perform instance validation in a comparable interface for operators with greater / lesser or equal ( http://docs.oracle.com/javase/8/ docs / api / java / lang / Comparable.html ).

0
source share

All Articles