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);
}
}