如何以更简洁优雅的方式执行Java函数式接口?
c("hello world") instead of c.accept("hello world"))? Great question! I totally get the urge to write more concise code—having to type .accept() every time you want to execute a Consumer does feel a bit verbose, right?
Unfortunately, Java’s syntax doesn’t support directly invoking a functional interface instance like a regular method (the way you might in languages like Kotlin or Scala). Functional interfaces in Java are still objects at their core, so you have to explicitly call their single abstract method (SAM)—in this case, Consumer.accept().
That said, there are a few ways to make your code feel more elegant and concise:
1. Skip the variable entirely (for one-off calls)
If you only need to execute the consumer once, you can inline the method reference and call accept() directly without assigning it to a variable:
((Consumer<String>) System.out::println).accept("hello world");
This cuts out the intermediate variable, though it’s a bit clunky if you need to reuse the consumer multiple times.
2. Create a utility method to wrap the call
You can write a simple static utility method to handle the accept() call for you, which makes the invocation look cleaner:
public class FunctionalUtils { public static <T> void run(Consumer<T> consumer, T value) { consumer.accept(value); } }
Then use it like this:
FunctionalUtils.run(System.out::println, "hello world");
This hides the .accept() call behind a more readable method name, and you can reuse this utility across your codebase.
3. Use var to simplify variable declaration (Java 10+)
If you’re using Java 10 or later, var lets you avoid repeating the Consumer<String> type when declaring your variable:
var c = System.out::println; c.accept("hello world");
It doesn’t eliminate the .accept() call, but it reduces boilerplate in the variable declaration.
4. Define a custom functional interface (if you really want a shorter method name)
If you’re willing to create a custom interface, you can define a SAM with a shorter name (though this is a bit overkill unless you use it frequently):
@FunctionalInterface public interface InvokableConsumer<T> { void invoke(T t); }
Then use it like:
InvokableConsumer<String> c = System.out::println; c.invoke("hello world");
This swaps .accept() for .invoke(), which is a bit shorter, but it’s still an explicit method call.
To wrap up: Java doesn’t have the syntax sugar to let you call c("hello world") directly, but the workarounds above can help you write cleaner, more concise code when working with functional interfaces.
内容的提问来源于stack exchange,提问作者beni0888

