2012-11-06 64 views
-1

我想知道是否可以通过将函数名称添加到参数来调用另一个函数。因此,例如,我想用4个部分制作脚本。每个部分都需要输入(我使用扫描仪,不要问为什么:P是它的任务),然后需要将其传递给另一个脚本,例如,计算和东西。通过将其添加到参数调用另一个函数

我这个开始的:

static int intKiezer(String returnFunctie, String text) { 

    Scanner vrager = new Scanner(System.in); 
    while (true) { 

     System.out.println(text); 
     int intGekozen = vrager.nextInt(); 

     if (vrager.hasNextInt()) { 

      returnFunctie(intGekozen); 
     } 

     else { 

      vrager.next(); 
      System.out.println("Verkeerde invoer!"); 
     } 
    } 

正如你看到的,我想通过努力把它(returnFunctie(intgekozen))所获得的价值推到另一个功能。它应该用intgekozen作为参数调用returnFunctie。但它不起作用

我会调用这样的函数:intKiezer(sphereCalculations, "What radius do you want to have?")。所以从输入的答案,如果其正确的应该传递给另一个函数称为sphereCalculations

+1

你的returnFunctie(...)代码在哪里? – kosa

+0

原则上这可能与反思,但真正的问题是:你为什么想这样做?这表明你的程序有一个奇怪的设计。 (反射只能用于特殊情况,我不想学习你的坏习惯)。 – Jesper

+0

事情是我有多个输入,我想为他们做一个功能。不仅仅是说明扫描仪的每种功能,例如,这对我来说似乎是最简单的方法,因为我只需添加文本和函数名称 –

回答

3

这是一个想法。

定义一个接口,该接口拥有一个可以执行任何计算的方法。例如:

interface Algorithm { 
    int execute(int value); 
} 

然后定义一个或多个类来实现接口并做任何你希望他们做的计算。例如:

class MultiplyByTwo implements Algorithm { 
    public int execute(int value) { 
     return value * 2; 
    } 
} 

class AddThree implements Algorithm { 
    public int execute(int value) { 
     return value + 3; 
    } 
} 

然后,写你的方法,使其接受一个Algorithm作为参数。用所需的值执行算法。

static int intKiezer(Algorithm algo, String text) { 
    // ... 

    return algo.execute(intGekozen); 
} 

通过传递接口Algorithm的实现类的一个实例调用你的方法。

int result = intKiezer(new MultiplyByTwo(), "Some question"); 
System.out.println("Result: " + result); 
+0

好吧,我明白了:)。唯一的是我还没有使用类。但是我试着用你告诉我的技巧编辑我的脚本。我不知道我是否正确使用它。不应该通过只加入return“returnFunctie.execute(intGekozen);” –

+0

+1如果你不想有太多类,你甚至可以匿名实现 – Jerome

1

正如@Jesper所说,这是可能的反思,也许只有反思。反射是对象可以分析自身并遍历其成员(属性和方法)的过程。就你而言,你似乎在寻找一种方法。

通过你的代码的外观,它看起来像你想要的是,实际上,将一个函数对象传递给你的代码,其中可以应用参数。这在Java中是不可能的。在Java 8中,类似的东西可能会增加闭包。你可以在Groovy中做到这一点,通过传递一个Closure作为参数,或支持闭包或函数的其他语言。

你可以得到接近你想要通过定义一个抽象类/接口,通过它的一个实例,以你的方法,然后调用传递参数给它,就像一个方法是什么:

interface Function <T> { 
    public Integer call(T t); 
} 


public class TestFunction { 
    static int intKiezer(Function<Integer> returnFunctie, String text) 
    { 
     int a = 10; 
     System.out.println(text); 

     return returnFunctie.call(a); 
    } 

    public static void main(String[] args) 
    { 
     Function<Integer> function = new Function<Integer>() { 
      public Integer call(Integer t) { return t * 2; } 
     }; 

     System.out.println(intKiezer(function, "Applying 10 on function")); 
    } 
} 

如果您意图是调用一个方法,那么你最好使用一些反射库。想起了Apache Common's MethodUtil。我认为这是你的男人:

invokeMethod(Object object, String methodName, Object arg) 
    Invoke a named method whose parameter type matches the object type. 
相关问题