简体   繁体   English

将方法作为参数传递

[英]Pass method as an argument

I have two similar methods:我有两种类似的方法:

public void methodOne() {
    final List<User> users = userService.getUsers();
    final Integer count = getCount();
    emailService.sendEmailOne(users, count);
}

public void methodTwo() {
    final List<User> users = userService.getUsers();
    final Integer count = getCount();
    emailService.sendEmailTwo(users, count);
}

The difference is - I'm sending different type of email.不同之处在于 - 我正在发送不同类型的 email。 Can I pass method name as an argument here to get something like:我可以在这里传递方法名称作为参数来获得类似的东西:

public void method(sendEmail) {
   final List<User> users = userService.getUsers();
    final Integer count = getCount();
    emailService.sendEmail(users, count);
}

The method headers in your first code snippet (eg public void methodOne { ) are not syntactically correct.您的第一个代码片段(例如public void methodOne { )中的方法标头在语法上不正确。 There are no parameter list after the method name.方法名后面没有参数列表。

To have the flexibility of choosing a method at runtime, you can create an interface with one abstract method, then implement it into two different classes and override it accordingly.为了在运行时灵活地选择方法,您可以使用一个抽象方法创建一个interface ,然后将其实现到两个不同的类中并相应地覆盖它。 Then you can use an instance of your interface as the parameter of method .然后你可以使用你的接口实例作为method的参数。

It should be something like this:它应该是这样的:

public interface Sender {
    abstract public void send();
}


public class SenderOne implements Sender {
    public void send() {
        // your implementation here
    }
}

public class SenderTwo implements Sender {
    public void send() {
        // your implementation here
    }
}

And finally:最后:

public void method (Sender sender) {
    //...
    sender.send();
}

There is a much faster and easier way to accomplish it.有一种更快更容易的方法来完成它。

This post here also includes some previous answers.此处的这篇文章还包括一些以前的答案。

The first class declarations are just to make the example compilable.第一个 class 声明只是为了使示例可编译。 The interesting parts start after the method getCount()有趣的部分在方法getCount()之后开始

package snippet;

import java.io.IOException;
import java.util.List;

public class LamdaExample {
    // dummy declarations
    static class User {}
    static class EmailService {
        public void sendEmailOne(final List<User> pUsers, final Integer pCount) {}
        public void sendEmailTwo(final List<User> pUsers, final Integer pCount) {}
    }
    static class UserService {
        public List<User> getUsers() {
            return null;
        }
    }

    public LamdaExample() {}
    private final UserService   userService     = new UserService();
    private final EmailService  emailService    = new EmailService();
    private Integer getCount() {
        return null;
    }

    // interesting part comes here

    public void methodOne() {
        System.out.println("LamdaExample.methodOne()");
        final List<User> users = userService.getUsers();
        final Integer count = getCount();
        emailService.sendEmailOne(users, count);
    }
    public void methodTwo() {
        System.out.println("LamdaExample.methodTwo()");
        final List<User> users = userService.getUsers();
        final Integer count = getCount();
        emailService.sendEmailTwo(users, count);
    }

    public void method(final Runnable sendEmail) {
        final List<User> users = userService.getUsers();
        final Integer count = getCount();
        sendEmail.run();
    }

    public static void main(final String[] args) {
        // simple runnable, see code above
        final LamdaExample t = new LamdaExample();
        t.method(() -> t.methodOne());
        t.method(() -> t.methodTwo());

        // extended special functional interface, see code below
        t.methodSpecial((p, q) -> t.methodX(p, q));
        t.methodSpecial((p, q) -> t.methodY(q, p));

    }

    // extended example starts here

    @FunctionalInterface
    interface MySpecialInterface {
        double specialMethod(String param1, Class<?> param2) throws IOException;
    }

    public void methodSpecial(final MySpecialInterface sendEmail) {
        final List<User> users = userService.getUsers();
        final Integer count = getCount();

        try {
            sendEmail.specialMethod("lol", this.getClass());
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }
    public double methodX(final String pP, final Class<?> pQ) {
        System.out.println("LamdaExample.methodX()");
        final List<User> users = userService.getUsers();
        final Integer count = getCount();
        emailService.sendEmailOne(users, count);
        return 123.456;
    }
    public double methodY(final Class<?> pQ, final String pP) {
        System.out.println("LamdaExample.methodY()");
        final List<User> users = userService.getUsers();
        final Integer count = getCount();
        emailService.sendEmailTwo(users, count);
        return 98.765;
    }


}

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

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