Hello. It's Kecho. ** Do you guys use method references? ** ** It's convenient and it's easier to read. With such a method reference. I will introduce some specifications that I should be careful about.
public class Main {
public static void main(String[] args) throws Exception {
Arrays.asList("test1", "test2").stream().forEach(System.out::println);
}
}
// test1
// test2
You are referencing a static method. You can also use it like this.
public class Main {
public static void main(String[] args) throws Exception {
Arrays.asList("test1", "test2").stream().map(String::toUpperCase).forEach(System.out::println);
}
}
// TEST1
// TEST2
You're calling toUpperCase from the String class. Easy to see and convenient.
We've also introduced static methods above, but you can also use instance methods.
class Customer {
public String getName() {
return "which1";
}
}
public class Main {
public static void main(String[] args) throws Exception {
Arrays.asList(new Customer(), new Customer()).stream().map(Customer::getName).forEach(System.out::println);
}
}
// which1
// which1
You can write in the same notation.
The following can be written with the same Customer :: getName
.
map(e -> Customer.getName(e)) //When calling a static method
map(e -> e.getName()) //When calling the instance method of the stored instance
What if I have both methods that I can reference? I mentioned that you can call static and instance methods in the same notation, but if you have both, which one will be used?
class Customer {
public String getName() {
return "which1";
}
static public String getName(Customer customer) {
return "which2";
}
}
public class Main {
public static void main(String[] args) throws Exception {
Arrays.asList(new Customer(), new Customer()).stream().map(Customer::getName).forEach(System.out::println);
}
}
↓ ↓ ↓ ↓ ↓ The correct answer is 3 compilation errors! I get an error statement like this.
both getName() and getName(Customer) from the type Customer are eligible
Japanese translation:
```Ambiguous method reference: Both getname () and getname (customer) of type customer are eligible```
You're getting a compile error because you don't know which one to look at.
# What should I be careful about after all?
This time I threw a compile error because both methods can be referenced.
However, there are some patterns that are difficult to understand at a glance and cannot be referenced, as shown below.
1. When the method cannot be referenced due to visibility
2. When the method name is slightly different
3. If the method arguments are different
etc
Which method is referenced may cause unexpected behavior by the developer.
# Summary
When dealing with objects using types implemented by the developer, it is safer to refrain from using method references.
Recommended Posts