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.
A static method reference refers to a static method in a specific class. Its syntax is className::staticMethodName , where className identifies the class and staticMethodName identifies the static method. An example is Integer::bitCount .
Static import is a feature introduced in the Java programming language that allows members (fields and methods) which have been scoped within their container class as public static , to be used in Java code without specifying the class in which the field has been defined.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With