你好,可以用JAVA实现函数指针吗 我正在尝试做这样的事情
void methodA
{
try
{
}
catch(Exception E)
{
methodB(Pass the function pointer pointing to methodA)
}
}
void methodB(fp some_function_pointer)
{
call some_function_pointer
}
最佳答案
不,但是你可以传递对象本身:
public class Foo {
void methodA() {
try {
}
catch(Exception e) {
bar.methodB(this)
}
}
}
public class Bar {
void methodB(Foo someFoo) {
someFoo.methodA();
}
}
如果您希望能够传递任何方法,则将此方法包装到一个 Runnable 或 Callable 中,例如:
public class Foo {
void methodA() {
try {
}
catch(Exception e) {
bar.methodB(new Runnable() {
@Override
public void run() {
Foo.this.methodA();
}
});
}
}
}
public class Bar {
void methodB(Runnable runnable) {
runnable.run();
}
}
关于java - 函数指针 - 传递对自身的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10868704/