【发布时间】:2011-05-15 20:48:15
【问题描述】:
在标记为 dup 之前,是的,我见过 Function Pointers in Java,不,它并没有真正回答我的问题,主要是因为我对 Java 还很陌生,所以我不太了解分配答案。
这是一种混合了 Java / C++ 的东西,在 Java 中有什么合理的方法可以做到这一点吗?
public class Foo {
private int _data;
/* various other functions */
public boolean test1( Foo other ) { /* do test */ }
public boolean test2( Foo other ) { /* do test */ }
public boolean test3( Foo other ) { /* do test */ }
public boolean test4( Foo other ) { /* do test */ }
}
public class Bar {
private Foo[] _foos = { /* Init an array of Foos */ };
public Bar doSomething() {
_foos = new Foo[4];
_foos[0] = getTest(Foo::test1);
_foos[1] = getTest(Foo::test2);
_foos[2] = getTest(Foo::test3);
_foos[3] = getTest(Foo::test4);
}
/*
* Now we only have a single function which takes function pointer.
*/
private Foo _getTest(boolean Foo::*func()) {
Foo current = _foos[ 0 ];
for ( int i = 1; i != _foos.length; i++ )
current = current.*func( _foos[ i ] ) ? _foos[ i ] : current;
return current;
}
}
【问题讨论】:
-
@ybungalobill:当您对一门语言足够陌生时,您可能没有足够的知识来提出特定问题。