说明int枚举模式是编译时常量是什么意思? [英] What does it mean to say that int enum patterns are compile-time constants?

查看:203
本文介绍了说明int枚举模式是编译时常量是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是来自Effective Java


使用int枚举模式的程序是脆弱的。因为int枚举是
编译时常量,所以它们被编译到使用它们的客户端中。


有些人可以解释为什么int枚举模式被称为编译类型常量,是什么意思编译到客户端



这是一个这样一个常数的例子:

  public static final int APPLE_FUJI = 0; 


解决方案

假设您有两个文件:

  Foo.java:
public class Foo
{
public static final int SOMETHING = 1;
}

Bar.java:
public class Bar
{
public static void main(String [] args)
{
System.out.println(Foo.SOMETHING);
}
}

编译它们,运行 java bar ,它将打印出来1。



现在更改Foo.java,以便 SOMETHING 是2,并重新编译只是Foo.java 。重新运行 java栏,它将仍然打印1.常量值将被复制到使用它的每一段代码,而不是要求

在实践中,如果您重新编译所有时间任何变化,这不是问题。


This is from Effective Java

Programs that use the int enum pattern are brittle. Because int enums are compile-time constants, they are compiled into the clients that use them.

Can some one explain why the int enum pattern is called compiled type constant and what is meant by compiled into the clients?

Here s' an example of such a constant :

public static final int APPLE_FUJI = 0;

解决方案

Suppose you have two files:

Foo.java:
public class Foo
{
    public static final int SOMETHING = 1;
}

Bar.java:
public class Bar
{
    public static void main(String[] args)
    {
        System.out.println(Foo.SOMETHING);
    }
}

Compile them both, run java Bar and it will print out 1.

Now change Foo.java so that SOMETHING is 2, and recompile just Foo.java. Rerun java Bar and it will still print 1. The constant value will be copied to every piece of code that uses it, rather than asking for the value from Foo at execution time.

In practice, if you recompile everything any time anything changes, this isn't a problem.

这篇关于说明int枚举模式是编译时常量是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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