Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a method reference on a static import?

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.

like image 890
Richard Deurwaarder Avatar asked Aug 16 '17 06:08

Richard Deurwaarder


People also ask

How do you reference a static method?

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 .

Can you import a static method?

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.


1 Answers

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.

like image 134
NPE Avatar answered Sep 30 '22 18:09

NPE