package day15_java_class; import java.util.Optional; /** * Optional类中要进行null相关处理 * @author asus *返回空数据:public static <T> Optional<T> empty(); *获取数据: public T get(); *保存数据,但是不容许出现null:public staic <T> Optional <T> of(T value) *如果保存数据时存在有null,抛出异常:NullPointerException异常 *保存数据允许为空:public static <T> Optional <T> ofNullable(T value) *空的时候返回其他数据:public T orElse(T other) */ interface IMessages{ public String getContent(); } class MessageImpl implements IMessages{ @Override public String getContent() { // TODO Auto-generated method stub return "welcome to !"; } } class MessageUtil{ private MessageUtil() {} public static Optional <IMessages> getMessage() { return Optional.of(new MessageImpl()); } public static void useMessage(IMessages msg) { if(msg != null) { System.out.println(msg.getContent()); }else { System.out.println("输入有误,不应为空。^ 。"); } } } public class java_Optional_class { public static void main(String[] args) { IMessages temp = MessageUtil.getMessage().orElse(new MessageImpl()); MessageUtil.useMessage(temp); } }
Use and introduction of Optional class for null related processing
Guess you like
Origin blog.csdn.net/qq_41663470/article/details/113770578
Recommended
Ranking