当前位置: 代码迷 >> 综合 >> JAVA8 Consumer接口站在实战角度告诉你那些不知道的事
  详细解决方案

JAVA8 Consumer接口站在实战角度告诉你那些不知道的事

热度:40   发布时间:2023-12-02 00:52:50.0
@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,然后调用accept,对这个参数做一系列的操作,没有返回值。

下面举例

例1:

public class ConsumerTest {public static void main(String[] args) {test(x -> {int y = x*x;System.out.println(y);});}private static void test(Consumer<Integer> action) {int a = 10;action.accept(a);System.out.println("a:" + a);}}

打印

100a: 10

调用accept()方法后,main中的x即入参经过操作后赋值y,打印是100。而test打印的a依然是10。

例2:

public class ConsumerTest {public static void main(String[] args) {Test.testTest(act -> {act.setXx(18);});}static class Test {public int xx;public int getXx() {return xx;}public void setXx(int xx) {this.xx = xx;}public static void testTest(Consumer<Test> action) {Test test = new Test();test.setXx(5);action.accept(test);System.out.println(test.getXx());}}
}

这个例子消费的是对象引用,我们给xx设置初值为5,然后消费test,在main中调用方法

testTest(Consumer<Test> action)后,xx变为了18。

总结:

    Consumer接口消费入参,没有返回值,对入参可做一系列操作,还可以解耦合。

如果对你有帮助帮忙点个赞哈

  相关解决方案