public class test18 { public static void main(String[] args) throws Throwable { System.out.println(test18.getOrderName()); } public static String getOrderName() throws Throwable { test16 t1 = new test16("zhang", "MsdUy"); 传统if 语句 // if (t1 != null) { // String orderName = t1.getOrderName(); // if (orderName != null) { // return orderName.toLowerCase(); // } // } OPtional 写法一: Object df = Optional.of(t1).map((Function<test16, Object>) test16 -> test16.getOrderName().toLowerCase()) .orElse("df"); return df.toString(); OPtional 写法二: String elseThrow = Optional.ofNullable(t1).map(x -> x.getOrderName()) .map(x -> x.toLowerCase()) .orElseThrow(new Supplier<Throwable>() { @Override public Throwable get() { return new Throwable("t1为空"); } }); return elseThrow; } }