命名约定:"from" 与 "of" 方法有什么区别
naming convention: What is the difference between "from" vs "of" methods
来自命名约定和可用性:
class 中的“from”和“of”方法有什么区别?什么时候创建每个?
请参阅 Oracle 提供的指南 Method Naming Conventions posted as part of the java.time tutorial。
引用:
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
来自命名约定和可用性: class 中的“from”和“of”方法有什么区别?什么时候创建每个?
请参阅 Oracle 提供的指南 Method Naming Conventions posted as part of the java.time tutorial。
引用:
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