【发布时间】:2019-05-17 19:08:53
【问题描述】:
在下面的代码中,我试图理解 java-8 中提供的 Optional 的概念。我创建了下面的示例来掌握 orElse() 背后的原理。 执行完代码,执行了defaultMethod()的body,并返回了
new User("DEFAULT_USER", "default@gmail.com", "0000", null);
反对y。日志语句按照我的预期打印了正确的数据。
问题是,为什么 defaultMethod() 内部的所有日志都没有打印出来?是否引入 orElse() 只返回值而不执行提供的方法的整个主体。?
代码:
@Override
protected void onResume() {
super.onResume();
User user_1 = this.getUser_1();
User user_2 = this.getUser_2();
User user_3 = this.getUser_3();
User y = OptionalsUtils.toOptional(user_1)
.map(u1 -> this.getUser_3())
.orElse(this.defaultMethod());
Log.i(TAG_LOG, "orElse->y: " + y.getUserName());
}
private User getUser_3() {
List<String> list = new ArrayList<String>(5);
list.add("espn");
list.add("qtv");
list.add("der Spiegel");
list.add("deutsch welle");
User user = new User();
user.setUserName("johannas");
user.setUserEmailAddres("joha90@gmail.com");
user.setUserId("2345");
user.setUserFavoritesTvList(null);
return null;
}
private User defaultMethod() {
Log.w(TAG_LOG, "defaultMethod is called1");
Log.w(TAG_LOG, "defaultMethod is called2");
Log.w(TAG_LOG, "defaultMethod is called3");
Log.w(TAG_LOG, "defaultMethod is called4");
Log.w(TAG_LOG, "defaultMethod is called5");
Log.w(TAG_LOG, "defaultMethod is called5");
Log.w(TAG_LOG, "defaultMethod is called5");
Log.w(TAG_LOG, "defaultMethod is called5");
return new User("DEFAULT_USER", "default@gmail.com", "0000", null);
}
日志:
2018-12-17 12:46:15.774 20158-20158/com.example.optionals_00 W/ActMain: defaultMethod is called1
2018-12-17 12:46:15.774 20158-20158/com.example.optionals_00 W/ActMain: defaultMethod is called2
2018-12-17 12:46:15.774 20158-20158/com.example.optionals_00 W/ActMain: defaultMethod is called3
2018-12-17 12:46:15.774 20158-20158/com.example.optionals_00 W/ActMain: defaultMethod is called4
2018-12-17 12:46:15.774 20158-20158/com.example.optionals_00 W/ActMain: defaultMethod is called5
2018-12-17 12:46:15.774 20158-20158/com.example.optionals_00 W/ActMain: defaultMethod is called5
2018-12-17 12:46:15.774 20158-20158/com.example.optionals_00 I/ActMain: orElse->y: DEFAULT_USER
【问题讨论】:
-
记录器是否可能决定不记录您传递给它的某些字符串,因为您传递了 4 次相同的字符串?
标签: java android java-8 optional