过于基础,就不废话了,实验代码如下:
package com.demo;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiPredicate;
import java.util.function.Function;
public class DoubleColonTest {
String str;
public DoubleColonTest(String str) {
this.str = str;
}
public static void main(String[] args) {
/**
* :: 双冒号表示方法引用
* 案例一:对象::实例方法
* public interface Consumer {
* void accept(T t);
* }
*
* public void println(Object x) {
* 此处省略
* }
*/
List list = Arrays.asList(1, 2, 3);
list.forEach(System.out::println);
System.out.println("------------分割线------------------");
/**
* 案例二:类::实例方法
* public interface BiPredicate {
* boolean test (T t, U u);
* }
*
* public boolean equals(Object obj) {
* return (this == obj);
* }
*/
System.out.println(testEquals(Object::equals, "a", "a"));
System.out.println("------------分割线------------------");
/**
* 案例三:类::静态方法
* public interface Function {
* R apply (T t);
* }
*
* public static int abs(int a) {
* return (a < 0) ? -a : a;
* }
*
* 总结:当方法的参数类型,参数个数,参数顺序与接口方法一致时,可以使用双冒号
* java内置了许多函数式接口,在java.util.function下。感兴趣的同学可以看下
*/
System.out.println(testAbs(Math::abs, -10));
System.out.println("------------分割线------------------");
/**
* 双冒号表示构造器引用,当构造器的参数类型,参数个数,参数顺序与接口方法一致时,可以使用双冒号
* public interface Function {
* R apply (T t);
* }
*
* public DoubleColonTest(String str) {
* this.str = str;
* }
*
*/
Function testFunction = DoubleColonTest::new;
testConstructor(testFunction, "hello world");
testConstructor(DoubleColonTest::new, "hello the world");
System.out.println("------------分割线------------------");
/**
* 双冒号表示数组引用,当方法的参数类型,参数个数,参数顺序与接口方法一致时,可以使用双冒号
* public interface Function {
* R apply (T t);
* }
*
* Integer [] integers = new Integer[t];
*/
testArray(Integer[]::new, 10);
}
public static boolean testEquals(BiPredicate biPredicate, Object obj1, Object obj2) {
return biPredicate.test(obj1, obj2);
}
public static Integer testAbs(Function function, Integer integer) {
return function.apply(integer);
}
public static void testConstructor(Function function, String str) {
DoubleColonTest test = function.apply(str);
System.out.println(test.str);
}
public static void testArray(Function function, Integer length) {
Integer[] apply = function.apply(length);
System.out.println(apply.length);
}
}