繁体   English   中英

在Java中将方法作为参数传递给方法

[英]Pass method to method as an argument in Java

我想将一个方法传递给一个方法作为参数,并且我想开发一个系统如下。

如何在Java中开发它?

伪代码:

class A
{
    public void test(Method method, Method method2)
    {
        if(Condition)
        {
            method.run();
        }
        else
        {
            method2.run();
        }
    }
}

class B
{
    A a = new A();
    a.test(foo(),bar());

    public void foo()
    {
        print "hello";
    }
    public void bar()
    {
    }
}

您没有通过方法。 您传递实现接口的类的对象。 在您的情况下,现有的Runnable接口将非常合适,因为它具有单个run方法,没有输入参数,也没有返回值。

class A
{
    public void test(Runnable method, Runnable method2)
    {
        if(Condition)
        {
            method.run();
        }
        else
        {
            method2.run();
        }
    }
}

class B
{
    public static void main (String[] args)
    {
        A a = new A();
        Runnable r1 = new Runnable() {
            public void run() {
                System.out.println("hello1");
            }
        };
        Runnable r2 = new Runnable() {
            public void run() {
                System.out.println("hello2");
            }
        };
        a.test(r1,r2);
    }
}

如果您使用的是Java 8,则可以使用lambda表达式简化语法:

class B
{
    public static void main (String[] args)
    {
        A a = new A();
        a.test(() -> System.out.println("hello1"),() -> System.out.println("hello2"));
    }
}

或者,您可以使用方法引用(同样,仅在Java 8中),编译器可以将其与test()方法所需的功能接口进行匹配:

class B
{
    public static void main (String[] args)
    {
        A a = new A();
        a.test(B::foo,B::bar); // though foo() and bar() must be static in this case,
                               // or they wouldn't match the signature of the run()
                               // method of the Runnable interface expected by test()
    }
}

这取决于您的方案和所使用的Java版本。

在Java中,使用带有匿名类的所谓的单一抽象方法接口功能接口是一种常见的模式。 您基本上是通过接口实现匿名类,并将结果对象传递给您的方法。 这适用于所有版本的Java。

// CheckPerson is the interface to implement
fetchPersons(
    new CheckPerson() {
        public boolean test(Person p) {
            return p.getGender() == Person.Sex.MALE
                && p.getAge() >= 18
                && p.getAge() <= 25;
        }
    }
);

Java 8重新创建了该概念,并提供了Lambda表达式 ,使事情变得更加优雅和实用。

fetchPersons(
    (Person p) -> p.getGender() == Person.Sex.MALE
        && p.getAge() >= 18
        && p.getAge() <= 25
);

除了上述解决方案之外,您可能还对Command Pattern感兴趣。

创建具有该方法签名的接口,并在您的方法实现中传递它的匿名子类。

创建一个类似包含您要作为参数传递的方法的接口:

 public interface methodInterface{

   method(parameter here);


}

然后在一个类中实现

然后为每种范围检查方法创建实现:

    public class class1 implements methodInterface{

    public method(//parameters here) {
        // do something
    }

}

然后,其他方法的签名变为:

public void enterUserInput(methodInterface method)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM