如何在类中使函数可变?

vau*_*uge 0 java

想象一下,我有一堂课

class A {
 int a;
 int b;

 A(int a, int b) {
  this.a=a; this.b=b;
 }

 int theFunction() {
   return 0;
 }

 void setTheFunction([...]) {
    [...]
 }
}
Run Code Online (Sandbox Code Playgroud)

对于我实例化的每个新对象,我希望能够theFunction()通过调用以新的方式定义setTheFunction( [...] ).例如,我想做这样的事情:

A test = new A(3,2);
test.setTheFunction ( int x = a*b; return x*x+2; );
System.out.println(test.theFunction()); // Should return (3*2)*(3*2)+2 = 38
Run Code Online (Sandbox Code Playgroud)

或类似的东西:

A test2 = new A(1,5);
test.setTheFunction ( for(int i=0; i<b; i++) a=a*b*i; return a; );
Run Code Online (Sandbox Code Playgroud)

现在,我当然可以做的是在A类中编写所有这些函数,并使用switch语句来确定要选择哪一个.但是,如果我不想theFunction()在我的A类内部硬编码算法,有没有办法做类似上面的事情?而且会是什么setTheFunction()模样?你必须通过什么类型的论证?

FTh*_*son 6

你可以用Callable.

public class A<V> {

    public int a;
    public int b;
    private Callable<V> callable;

    public A(int a, int b) {
        this.a = a;
        this.b = b;
    }

    public V theFunction() {
        try {
            return callable.call();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void setTheFunction(Callable<V> callable) {
        this.callable = callable;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,使用它:

final A<Integer> test = new A<Integer>(3, 2);
test.setTheFunction(new Callable<Integer>() {
    int x = test.a * test.b;
    return x * x + 2;
});
System.out.println(test.theFunction());
Run Code Online (Sandbox Code Playgroud)

当然,通用打字A是没有必要的,但我已添加它以使这个答案受到更少的限制.