When using map functions in java I can do the following:
import com.example.MyClass;
someStream.map(MyClass::myStaticMethod)
but in my project we sometimes use static imports, how can I reference the myStaticMethod when the import is static?
I would think this would work but it doesn't:
import static com.example.MyClass.myStaticMethod;
someStream.map(myStaticMethod); //does not compile
Why does this not work? Am I 'stuck' with using the first example or are there other solutions.
Let's look at the relevant part of the Java Language Specification, 15.13. Method Reference Expressions.
It lists the following ways to a create method reference:
MethodReference:
ExpressionName :: [TypeArguments] Identifier
ReferenceType :: [TypeArguments] Identifier
Primary :: [TypeArguments] Identifier
super :: [TypeArguments] Identifier
TypeName . super :: [TypeArguments] Identifier
ClassType :: [TypeArguments] new
ArrayType :: new
Note that all of them include a ::
token.
Since the argument to someStream.map(myStaticMethod)
does not include ::
, it is not a valid method reference.
This suggests that you do need to import MyClass
(perhaps in addition to the static import, if that's your preference) and refer to the method as MyClass::myStaticMethod
.