函数式接口的几个比较容易搞错的误区

/ 默认分类 / 0 条评论 / 782浏览

函数式接口的几个比较容易搞错的误区

java8开始引入了函数式接口这一概念,相信大家很早就使用过了,最常见的比如Runable接口,这就是一个函数式接口,关于函数式接口的一些基础的介绍这里就不再展开了,下面是我之前遇到的一些坑

先来看一下Runable接口

@FunctionalInterface
public interface Runnable {
  
    public abstract void run();
}

可以看到@FunctionalInterface这个注解,这就表明了Runable是一个函数式接口 相信大家都有这样的认识:函数接口就是接口中有且只有一个抽象方法,比如下面

public interface TestInter{
	String hello();
	
	default String {return "whatsoft.cn"}
}

上面的接口其实也是一个函数式接口,虽然不止一个方法,但是另一个方法不是抽象方法,是有方法实现的default方法 下面再来看下Comparator接口

@FunctionalInterface
public interface Comparator<T> {
    
    int compare(T o1, T o2);

    boolean equals(Object obj);
	
    default Comparator<T> reversed() {
        return Collections.reverseOrder(this);
    }

    default Comparator<T> thenComparing(Comparator<? super T> other) {
        Objects.requireNonNull(other);
        return (Comparator<T> & Serializable) (c1, c2) -> {
            int res = compare(c1, c2);
            return (res != 0) ? res : other.compare(c1, c2);
        };
    }

从注解可以看出来,这其实也是一个函数式接口,但是我们发现,这个接口中有两个抽象方法,我去这就有点搞笑了,不是说函数式接口中只能包含一个抽象方法吗?这个问题的答案其实FunctionalInterface这个接口的源码注释中已经告诉我们了

/**
 * Conceptually, a functional interface has exactly one abstract
 * method.  Since {@linkplain java.lang.reflect.Method#isDefault()
 * default methods} have an implementation, they are not abstract.  If
 * an interface declares an abstract method overriding one of the
 * public methods of {@code java.lang.Object}, that also does
 * <em>not</em> count toward the interface's abstract method count
 * since any implementation of the interface will have an
 * implementation from {@code java.lang.Object} or elsewhere.
 
 * <p>However, the compiler will treat any interface meeting the
 * definition of a functional interface as a functional interface
 * regardless of whether or not a {@code FunctionalInterface}
 * annotation is present on the interface declaration.
 *
 * @jls 4.3.2. The Class Object
 * @jls 9.8 Functional Interfaces
 * @jls 9.4.3 Interface Method Body
 * @since 1.8
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface FunctionalInterface {}
public void test008394021(List<String> list)
    {
        list.sort(String::compareTo);
		//其实也就是list.sort((String s1,String s2) -> {s1.compareTo(s2)})
        System.out.println(list);
    }