Java&编译时常数 [英] Java & Compile-Time Constants

查看:86
本文介绍了Java&编译时常数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将为原语或 String 类型的静态最终变量变量定义一个值作为Java编译器的 REAL 编译时常数?
这样的变量是否会获得其他语言(例如C ++)的编译常数所具有的性能优势?

Will a static final variable of a primitive or String type, that is assigned a value at definition be considered as a REAL compile-time constant by the Java Compiler?
Will such a variable gain the performance bonus a compile-constant has in other languages, say C++?

原始值或 String 的枚举是否被编译器视为常量?

Are enums of primitive or String values get treated like constants by the compiler?

据我了解,在不影响脚本工作的情况下,用常量代替变量总是很有益的,因此我想知道 const 关键字。

From what I understand, it is always good to substitute variables with constants when it doesn't effect workings of the script and so I wonder at the empty meaning for the const keyword in java.
Thanks in advance.

推荐答案

是的,它们可以编译-时间常数。例如,代码

Yes, they're compile-time constants. For example, the code

private static final boolean DEBUG = false;

...

if (DEBUG) {
   // some code
}

将被编译为甚至不包含 if 内部代码的字节码。

will be compiled to bytecode which doesn't even contain the code inside the if. It will be removed by the compiler.

如果决定更改其值,则必须重新编译所有引用该常量的类。

And you have to recompile all the classes referencing the constant if you decide to change its value.

但是请注意,它只是无法修改的引用。可以更改对象的内容(如果它是可变的)。例如,可以修改以下代码中的数组或StringBuilder的内容:

Note however that it's only the reference that can't be modified. The content of the object (if it's mutable), can be changed. For example, the content of the array or StringBuilder in the following code may be modified:

// don't do this:
public static final String[] seasons = new String[] {"Spring", "Summer", "Autumn", "Winter"};
public static final StringBuilder someBuffer = new StringBuilder("foo");

您关于枚举的问题没有道理。没有原始或STring的枚举。每个枚举定义自己的类。

Your question about enums doesn't make sense. There is no enum of primitive or STring. Each enum defines its own class.

这篇关于Java&编译时常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆