java中将方法当作参数传递的方式

1. 使用consumer接口

Java8中引入了一个函数式接口Consumer的对象,该对象可以把方法作为参数进行传递。

接口定义:

@FunctionalInterface
public interface Consumer<T> {
 
    
    void accept(T t);
 
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}

该接口接收一个泛型参数T,然后可以自定义实现Consumer接口中的accept方法来对T进行一系列的操作,该方法没有返回值。

示例:

void testConsumer(Integer id, Consumer consumer, String msg){
	consumer.accept(msg);
}

public static void main(String[] args){
	testConsumer(System.out::println, "consumer接口测试...");
	testConsumer(x -> {
			x = StringUtils.join(x,String.valueof(x).length());
			System.out.println(x);
		}, "consumer接口测试...")
}

#   输出结果
接口测试...
接口测试...15

其实,主要是理解Consumer消费者,就可以了~主要是对入参做一些列的操作,在stream里,主要是用于forEach;内部迭代的时候,对传入的参数,做一系列的业务操作,没有返回值;

这个接口,只有一个默认方法,看下注释内容,就清楚用法了,就不在写案例解释了

	/**传入一个Consumer类型的参数,
	 *他的泛型类型,
	 *跟本接口是一致的T,先做本接口的accept操作,
	 *然后在做传入的Consumer类型的参数的accept操作
	*/
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }

2. 基于lambda表达式

示例:

public class TestClass {

    interface TestFunction<T>{
        boolean getBooleanValue(T t);
    }

    static class Student{
        String name;
        Double score;

        Student(String name, Double score) {
            this.name = name;
            this.score = score;
        }

        Double getScore() {
            return score;
        }
    }
    static <T> void printMsg(T obj, TestFunction<T> function){
        if(function.getBooleanValue(obj)){
            System.out.println("result is true");
        }else{
            System.out.println("result is false");
        }
    }

    public static void main(String[] args) {
        printMsg(new Student("张三",92.5),x->{
            return x.getScore().compareTo(90d) > 0;
        });
        printMsg(new Student("张三",80.5),x->{
            return x.getScore().compareTo(90d) > 0;
        });
    }
}

# 输出结果
result is true
result is false

3. 参考

  1. https://blog.csdn.net/qq_28410283/article/details/80618456
  2. https://blog.csdn.net/qq_44964202/article/details/114992507
  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值