简体   繁体   中英

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?

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.

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 :

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 :

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.

Using so called single abstract method interfaces or functional interfaces with anonymous classes is a common pattern in 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.

// 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.

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 .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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