Skip to content

Method Reference Pattern (Class::StaticMethod)

The Method Reference Pattern (Class::StaticMethod) is a specific syntax in Java 8 functional programming used to pass an existing static method as an argument where a Functional Interface is expected.^[600-developer-java-java8-java8-lambda01.md]

This pattern is often utilized to extract and reuse logic, effectively treating a static method as a lambda expression that fulfills a specific functional contract (e.g., a BiFunction).^[600-developer-java-java8-java8-lambda01.md]

Syntax

The syntax follows the format ClassName::staticMethodName.^[600-developer-java-java8-java8-lambda01.md]

For example, given a class BeanDao with a static method currentSql, the method reference is written as BeanDao::currentSql.^[600-developer-java-java8-java8-lambda01.md]

Usage Example

This pattern is frequently used in conjunction with "template method" designs to handle cross-cutting concerns like connection management.^[600-developer-java-java8-java8-lambda01.md]

In the following example, DefaultBO.read accepts a Functional Interface (BiFunctionUnchecked) and a map. The static method BeanDao::currentSql is passed as the function implementation:

private static List<OhSystemConfig> simpleBoMethod(Map<String, Object> map) throws Exception {
    return DefaultBO.read(map, BeanDao::currentSql); // 類名-靜態方法名
}

In this context, the read template manages the database connection lifecycle, while the referenced static method (currentSql) provides the specific execution logic.^[600-developer-java-java8-java8-lambda01.md]

  • [[Lambda Expressions]]
  • [[Functional Interfaces]]
  • [[Template Method Pattern]]

Sources

^[600-developer-java-java8-java8-lambda01.md]