What does it mean to say that int enum patterns are compile-time constants?

╄→гoц情女王★ 提交于 2019-12-09 02:33:07

问题


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;

回答1:


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.




回答2:


The value '0' itself will be built into the .class files during compilation. If you then change that value, you have to recompile everything that uses it, including any client's code that uses your application/library.

If you don't, you won't get a warning, but rather incorrect behaviour.

If your compile-time constant is used solely in your code then it's less of a problem, assuming a complete clean/build cycle. If your code then reaches a wider audience then this becomes more of a problem.



来源:https://stackoverflow.com/questions/11773441/what-does-it-mean-to-say-that-int-enum-patterns-are-compile-time-constants

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!