Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

however this will not use the compiled intern'd string, it will create a new one on the old gen. Not a huge big deal, and 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...