How to use a method reference on a static import?

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.

Leave a Comment

tech