关闭。这个问题是opinion-based .它目前不接受答案。
想改善这个问题吗?更新问题,以便可以通过 editing this post 用事实和引文回答问题.
3个月前关闭。
Improve this question
从命名约定和可用性:
类中的“from”与“of”方法有什么区别?什么时候创建每个?
最佳答案
看指南Method Naming Conventions作为 the java.time tutorial 的一部分发布由 Oracle 提供。
报价:
of
Creates an instance where the factory is primarily validating the input parameters, not converting them.
… 和 …
from
Converts the input parameters to an instance of the target class, which may involve losing information from the input.
有关实际示例,请参阅 java.time 类,例如
LocalDate
, LocalTime
, Instant
, OffsetDateTime
, ZonedDateTime
, LocalDateTime
, 等等。LocalDate x = LocalDate.of( 2021 , Month.MARCH , 27 ) ; // Directly injecting the three parts of a date (year, month, day) without any need to parse or process the inputs other than basic data validation such as day within appropriate range of 1-28/31 for that year-month.
ZoneId zoneId = ZoneId.of( "Africa/Casablanca" ) ; // This string is the official name of this time zone. Can be mapped directly from name to object, with no real processing, parsing, or conversions involved.
ZonedDateTime zdt = ZonedDateTime.now( zoneId ) ;
LocalDate y = LocalDate.from( zdt ) ; // Converting between types. Data loss involved, losing (a) time-of-day and (b) time zone.
LocalDate z = zdt.toLocalDate() ;
见 code run live at IdeOne.com .x.toString(): 2021-03-27
y.toString(): 2021-05-25
z.toString(): 2021-05-25
关于java - 命名约定 : What is the difference between "from" vs "of" methods,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67680011/