命名约定:“from”与“of”方法有什么区别

ans*_*nie 3 java design-patterns naming-conventions

从命名约定和可用性来看:类中“from”与“of”方法有什么区别?何时创建每一个?

Bas*_*que 6

请参阅作为Oracle 提供的java.time教程的一部分发布的指南方法命名约定。

\n

去引用:

\n
\n

of

\n

创建一个实例,其中工厂主要验证输入参数,而不是转换它们。

\n
\n

\xe2\x80\xa6 和 \xe2\x80\xa6

\n
\n

from

\n

将输入参数转换为目标类的实例,这可能会丢失输入中的信息。

\n
\n

有关实际示例,请参阅java.time类,例如LocalDateLocalTimeInstantOffsetDateTimeZonedDateTimeLocalDateTime等。

\n
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.\n\nZoneId 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.\nZonedDateTime zdt = ZonedDateTime.now( zoneId ) ;\nLocalDate y = LocalDate.from( zdt ) ;                    // Converting between types. Data loss involved, losing (a) time-of-day and (b) time zone.\nLocalDate z = zdt.toLocalDate() ;\n
Run Code Online (Sandbox Code Playgroud)\n

查看IdeOne.com 上实时运行的代码

\n
x.toString(): 2021-03-27\ny.toString(): 2021-05-25\nz.toString(): 2021-05-25\n
Run Code Online (Sandbox Code Playgroud)\n