本文介绍了Java中最接近函数指针的替代品是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大约十行代码的方法.我想创建更多的方法来做完全相同的事情,除了一个会改变一行代码的小计算.这是传入函数指针以替换该行的完美应用程序,但 Java 没有函数指针.我最好的选择是什么?

I have a method that's about ten lines of code. I want to create more methods that do exactly the same thing, except for a small calculation that's going to change one line of code. This is a perfect application for passing in a function pointer to replace that one line, but Java doesn't have function pointers. What's my best alternative?

推荐答案

匿名内部类

假设您想要传入一个带有 String 参数的函数,该参数返回一个 int.
首先,如果您不能重用现有的接口,您必须定义一个以函数为唯一成员的接口.

Say you want to have a function passed in with a String param that returns an int.
First you have to define an interface with the function as its only member, if you can't reuse an existing one.

interface StringFunction {
    int func(String param);
}

采用指针的方法将只接受 StringFunction 实例,如下所示:

A method that takes the pointer would just accept StringFunction instance like so:

public void takingMethod(StringFunction sf) {
   int i = sf.func("my string");
   // do whatever ...
}

并且会被这样调用:

ref.takingMethod(new StringFunction() {
    public int func(String param) {
        // body
    }
});

在 Java 8 中,您可以使用 lambda 表达式调用它:

In Java 8, you could call it with a lambda expression:

ref.takingMethod(param -> bodyExpression);

这篇关于Java中最接近函数指针的替代品是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 01:15