Search code examples
javainliningcompile-time-constant

Are all compile-time constants inlined?


Let's say I have a class like this:

class ApplicationDefs{
public static final String configOption1 = "some option";
public static final String configOption2 = "some other option";
public static final String configOption3 = "yet another option";
}

Many of the other classes in my application are using these options. Now, I want to change one of the options alone and deploy just the compiled class. But if these fields are in-lined in the consumer classes this becomes impossible right?

Is there any option to disable the in-lining of compile time constants?


Solution

  • You can use String.intern() to get the desired effect, but should comment your code, because not many people know about this. i.e.

    public static final String configOption1 = "some option".intern();
    

    This will prevent the compile time inline. Since it is referring to the exact same string that the compiler will place in the perm, you aren't creating anything extra.

    As an alternative you could always do

    public static final String configOption1 = "some option".toString();
    

    which might be easier to read. Either way, since this is a bit odd you should comment the code to inform those maintaining it what you are doing.

    Edit: Found another SO link that gives references to the JLS, for more information on this. When to use intern() on String literals