在Java中函数指针的最接近的替代是什么? [英] What's the nearest substitute for a function pointer in Java?

查看:130
本文介绍了在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 param的函数,返回 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中函数指针的最接近的替代是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆