使用函数式接口Supplier来实例化接口默认方法,Supplier对于给定的泛型类型产生一个实例,不需要任何参数。
接口:DefaultMethodInterface
package com.ven.java8.defaultmethod.Inteface; /** * jva8接口默认方法 * @author xiaowen0623 * */ public interface DefaultMethodInterface { /** * 接口静态变量 */ public static final String TYPE="JAVA8"; /** * 接口静态变量 */ public static final String ZW="JAVA WEB开发工程师"; /** * 接口方法 * * @param userName */ public void execute(String userName); /** * 默认方法 * * @param userName */ default void learn(String userName) { System.out.println(userName + "正在学习"+TYPE+"。。。。。。"); } /** * 默认的静态方法 * * @param userName * @return */ public static String learnStr(String userName) { String result = userName + " " + "是一名"+ZW; return result; }; }接口工厂:
package com.ven.java8.defaultmethod.Inteface; import java.util.function.Supplier; /** * 接口工厂 * 使用Supplier供应接口产生一个给定泛型的对象 * @author xiaowen0623 * */ public interface DefaulableFactory { /** * 通过函数接口Defaulable的实例 * @param supplier * @return */ static DefaultMethodInterface create(Supplier<DefaultMethodInterface> supplier){ return supplier.get(); }; }Supplier接口源代码:
/* * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package java.util.function; /** * Represents a supplier of results. * * <p>There is no requirement that a new or distinct result be returned each * time the supplier is invoked. * * <p>This is a <a href="package-summary.html">functional interface</a> * whose functional method is {@link #get()}. * * @param <T> the type of results supplied by this supplier * * @since 1.8 */ @FunctionalInterface public interface Supplier<T> { /** * Gets a result. * * @return a result */ T get(); }测试:
package com.ven.java8.defaultmethod.Inteface.test; import com.ven.java8.defaultmethod.Inteface.DefaulableFactory; import com.ven.java8.defaultmethod.Inteface.DefaultMethodImpl; import com.ven.java8.defaultmethod.Inteface.DefaultMethodInterface; /** * 测试接口默认方法 * @author xiaowen0623 * */ public class TestFactory { public static void main(String[] args) { //使用DefaultMethodImpl::new 使用java8新的方法引用方式 DefaultMethodInterface d = DefaulableFactory.create(DefaultMethodImpl::new); d.execute("xiaowen"); } }