Java中是否有与C++成员函数指针相同的东西?

Rob*_*nes 2 c++ java

在你标记为dup之前,是的,我已经在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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Aff*_*ffe 8

不,Java中根本就没有函数这样的东西.只有对象和方法完全由对象拥有并从属于它们.对象是你在java中的主人和主人,没有任何事情可以通过他的意志发生.

您可以通过使对象实现委托接口来实现一种java委托,这种接口尽可能接近.

public interface Func {

boolean func(Foo foo);

}

public class Test1 implements Func {

@Override
public boolean func(Foo foo) {
  return doSomeStuff();
}

...

_foos[0] = getTest(new Test1());
Run Code Online (Sandbox Code Playgroud)

希望这足以让我们了解这个想法.通常,您没有看到在应用程序代码中实际上做得太多.

编辑:

由于您是Java新手,因此实际执行您尝试执行的操作的语法.这也可能说明它是什么皮塔饼以及为什么人们不喜欢它:)

public class Bar {

  public static interface Func {
    boolean func(Foo current, Foo other);
  }

  public static Func test1 = new Func() {
    @Override
    public boolean func(Foo current, Foo other) {
      return current.test1(other);
    }
  };

  public Bar doSomething() {
    _foos = new Foo[4];
    _foos[0] = getTest(test1);
    //...
  }

  private Foo _getTest(Func func) {
    Foo current = _foos[ 0 ];

      for ( int i = 1; i != _foos.length; i++ ) {
        current = func(current, _foos[ i ] ) ? _foos[ i ] : current;
      }
    return current;
  }

}
Run Code Online (Sandbox Code Playgroud)