gpt4 book ai didi

java - 在 B 类中引用 A 类的公共(public)最终静态字符串是否会增加编译后的 B 类的大小?

转载 作者:行者123 更新时间:2023-12-03 22:52:34 25 4
gpt4 key购买 nike

假设有以下类:

class A {
public static final String someString = "thisIsSomeString";

// then potentially lots of non static members and functions.

}

class B {
void foo1() {
String someStringFromA = A.someString;
}

// OR

void foo2() {
String someStringFromA = "thisIsSomeString";
}

}

在这里,b.foo 应该是 foo1foo2foo1 的好处很简单:只有一个地方可以定义字符串名称,如果我们需要更改它,只需在这里更改即可。但有人告诉我,使用 foo1 会以某种方式将 A 的代码“导入”到 B 中,因此使用 foo1 而不是 foo2。这是真的?我假设使用 foo1 等同于 C#define。

最佳答案

实际上两者都会导致常量被内联到 B.class 中,所以没有区别。通常,选择更具可读性/可维护性的选项。

这是我得到的字节码:

void foo1();
Code:
0: ldc #3 // String thisIsSomeString
2: astore_1
3: return

void foo2();
Code:
0: ldc #3 // String thisIsSomeString
2: astore_1
3: return

关于java - 在 B 类中引用 A 类的公共(public)最终静态字符串是否会增加编译后的 B 类的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15367365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com