如何在Java中将方法作为参数传递? [英] How do I pass method as a parameter in Java?

查看:2242
本文介绍了如何在Java中将方法作为参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Java Pass方法作为参数

是否可以通过一个方法作为Java中的参数?如果我不能在不重复代码的情况下为下面的方法做出最佳的行动方案。

Is it possible to pass a method as a parameter in Java? If I can't what would be the best course of action for the method below without having to repeat code.

public void enterUserInput(javax.swing.JTextField inputField, javax.swing.JTextField   outputField, method rangeChecking){

    String input;
    double output;
    input = inputField.getText();
    output = Double.parseDouble(input);
    if(rangeChecking(output)){
        outputField.setText(input);
        inputField.setText(null);
    }

我将从不同的班级调用rangeChecking方法,每次调用enterUserInput rangeChecking方法将是不同的

I will be calling a rangeChecking method from a different class and each time I call the enterUserInput the rangeChecking method will be different

推荐答案

你应该使用 interface 来做这件事。

You should use an interface to do it.

你传递声明的界面方法的所需功能,并调用所需的方法。将被调用的具体方法是由实现类实现的方法。

You pass the interface that declares the desired function to the method, and invoke the desired method. The specific method that will be invoked is the one implemented by the implementing class.

它被称为策略设计模式

代码示例:

public static interface Foo { //this is the interface declaration
    public void print();
}
public static class Bar implements Foo { //Bar is an implementing class
    public void print() {
        System.out.println("Bar");
    } 

}
public static void test(Foo foo) { //the method accepts an interface
    foo.print(); //and invokes it, the implementing class' print() will be invoked.
}
public static void main(String... args) throws Exception {
    test(new Bar()); //invoke test() with the class implementing the interface
}

这篇关于如何在Java中将方法作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆