将 List 设置为常量是否明智且高效?
Is it sensible and efficient to set a List as a constant?
Google 的 Oauth2 库方法需要范围参数的 Java 列表。将参数编码为 List
文字是否明智,如下所示:
public static final List<String> YOUTUBE_SCOPES = Lists.newArrayList(
"https://www.googleapis.com/auth/youtube.upload",
"https://www.googleapis.com/auth/youtube.readonly");
这样我就可以:
SendToGoogleUtils.getGoogleAccountCredential(activity, accountName, YOUTUBE_SCOPES );
Java 编译器会创建高效的 YOUTUBE_SCOPES 文字吗?
ArrayList
不是不可变的,即使它们被声明为 final
;那只是意味着那个变量不能改变,但它的内容可以。参见:Why can final object be modified?
由于您使用的是 Lists.newArrayList
,看起来您使用的是 Guava。 Guava 对此问题有很好的解决方案:ImmutableList
。所以你的代码将是:
public static final List<String> YOUTUBE_SCOPES = ImmutableList.of(
"https://www.googleapis.com/auth/youtube.upload",
"https://www.googleapis.com/auth/youtube.readonly");
也就是说,这里还有另一个问题,那就是 "what if I want to change this later"?
我不知道您是否加载了任何类型的配置文件,但请注意,如果您确实需要更改这些范围(如果 Google 更改 URL),您将必须更改您的链接。如果这可以通过重新编译你的 jar 来改变,那么不要担心;不过,您可能需要考虑将这些神奇常量放入某种配置文件中。
List.of
现代 Java
在 Java 9 及更高版本中,我们有 List.of
methods to easily produce an unmodifiable List
.
public static final List<String> YOUTUBE_SCOPES =
List.of(
"https://www.googleapis.com/auth/youtube.upload",
"https://www.googleapis.com/auth/youtube.readonly"
)
;
Google 的 Oauth2 库方法需要范围参数的 Java 列表。将参数编码为 List
文字是否明智,如下所示:
public static final List<String> YOUTUBE_SCOPES = Lists.newArrayList(
"https://www.googleapis.com/auth/youtube.upload",
"https://www.googleapis.com/auth/youtube.readonly");
这样我就可以:
SendToGoogleUtils.getGoogleAccountCredential(activity, accountName, YOUTUBE_SCOPES );
Java 编译器会创建高效的 YOUTUBE_SCOPES 文字吗?
ArrayList
不是不可变的,即使它们被声明为 final
;那只是意味着那个变量不能改变,但它的内容可以。参见:Why can final object be modified?
由于您使用的是 Lists.newArrayList
,看起来您使用的是 Guava。 Guava 对此问题有很好的解决方案:ImmutableList
。所以你的代码将是:
public static final List<String> YOUTUBE_SCOPES = ImmutableList.of(
"https://www.googleapis.com/auth/youtube.upload",
"https://www.googleapis.com/auth/youtube.readonly");
也就是说,这里还有另一个问题,那就是 "what if I want to change this later"?
我不知道您是否加载了任何类型的配置文件,但请注意,如果您确实需要更改这些范围(如果 Google 更改 URL),您将必须更改您的链接。如果这可以通过重新编译你的 jar 来改变,那么不要担心;不过,您可能需要考虑将这些神奇常量放入某种配置文件中。
List.of
现代 Java
在 Java 9 及更高版本中,我们有 List.of
methods to easily produce an unmodifiable List
.
public static final List<String> YOUTUBE_SCOPES =
List.of(
"https://www.googleapis.com/auth/youtube.upload",
"https://www.googleapis.com/auth/youtube.readonly"
)
;