Java8自定义函数

Java8自定义函数


package com.jd.svc.jdk8;

import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;

public class ConstructorTest {

    public ConstructorTest() {
        System.out.println("没有参数");
    }

    public ConstructorTest(String oneArg) {
        System.out.println(oneArg);
    }

    public ConstructorTest(String oneArg, String twoArg) {
        System.out.println(oneArg + ":" + twoArg);
    }

    public static void main(String[] args) {
        Supplier<ConstructorTest> noArg = ConstructorTest::new;
        Function<String, ConstructorTest> oneArg = ConstructorTest::new;
        BiFunction<String, String, ConstructorTest> twoArg = ConstructorTest::new;

        System.out.println("==========================");

        noArg.get();
        oneArg.apply("x");
        twoArg.apply("y", "z");

        System.out.println("==========================");

        testMyFunction();
    }


    public static void testMyFunction() {
        Apple apple = new Apple("red");
        Runnable run = apple::toString;
        run.run();

        Apple appleGreen = new Apple("green");
        Runnable run1 = appleGreen::toString;
        run1.run();

        MyFunction fun = Apple::test;

        fun.fun(apple, "a", 3);

        MyFunction1 fun1 = Apple::test1;
        fun1.fun("x", 5);

        MyFunction2 fun2 = Apple::test2;
        fun2.fun(apple, "a");

        BiConsumer<String, Integer> test1 = Apple::test1;
    }

    static class Apple {

        private static String color;

        public Apple(String color) {
            this.color = color;
        }

        public void test(String str, Integer val) {
            System.out.println(str + ":" + val + ":" + this.color);
        }

        public static void test1(String str, Integer val) {
            System.out.println(str + ":" + val + ":" + color);
        }

        public void test2(String str) {
            System.out.println(str + ":" + this.color);
        }

        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder("Apple{");
            sb.append("color='").append(color).append('\'');
            sb.append('}');
            System.out.println(sb.toString());
            return sb.toString();
        }
    }


    public interface MyFunction {
        void fun(Apple apple, String str, Integer val);
    }

    public interface MyFunction1 {
        void fun(String str, Integer val);
    }

    public interface MyFunction2 {
        void fun(Apple apple, String str);
    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值