简体   繁体   English

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

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

I want to pass a method to a method as an argument and I want to develop a system as follows. 我想将一个方法传递给一个方法作为参数,并且我想开发一个系统如下。

How can I develop it in java? 如何在Java中开发它?

Pseudo code: 伪代码:

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()
    {
    }
}

You don't pass a method. 您没有通过方法。 You pass an object of a class implementing an interface. 您传递实现接口的类的对象。 In your case, the existing Runnable interface will fit nicely, since it has a single run method with no input arguments and no return value. 在您的情况下,现有的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);
    }
}

If you are using Java 8, you can simplify the syntax with lambda expressions : 如果您使用的是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"));
    }
}

Or you can use method references (again, only in Java 8), which the compiler can match to the functional interface expected by the test() method : 或者,您可以使用方法引用(同样,仅在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()
    }
}

It depends on your scenario and the version of Java you are using. 这取决于您的方案和所使用的Java版本。

Using so called single abstract method interfaces or functional interfaces with anonymous classes is a common pattern in Java. 在Java中,使用带有匿名类的所谓的单一抽象方法接口功能接口是一种常见的模式。 You are basically implementing an anonymous class via an interface and pass the resulting object to your methods. 您基本上是通过接口实现匿名类,并将结果对象传递给您的方法。 This works for all versions of 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 recreates that concept and provides Lambda Expressions which makes things more elegant and functional. Java 8重新创建了该概念,并提供了Lambda表达式 ,使事情变得更加优雅和实用。

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

Apart from the solutions above, you might be interested in the Command Pattern . 除了上述解决方案之外,您可能还对Command Pattern感兴趣。

Create an interface with that method signature, and pass an anonymous subclass of it with your method implementation. 创建具有该方法签名的接口,并在您的方法实现中传递它的匿名子类。

create an interface like containing the method u want to pass as argument : 创建一个类似包含您要作为参数传递的方法的接口:

 public interface methodInterface{

   method(parameter here);


}

Then implement it in a class 然后在一个类中实现

Then create implementations for each of your range checking methods: 然后为每种范围检查方法创建实现:

    public class class1 implements methodInterface{

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

}

Then your other method's signature becomes: 然后,其他方法的签名变为:

public void enterUserInput(methodInterface method)

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

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