簡體   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