导入的java类中的public

导入的java类中的public

本文介绍了导入的java类中的public static final变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我碰巧在工作场所遇到过Java代码。这是场景:有2个类 - ClassA ClassB

I happen to come across a Java code at my work place. Here's the scenario: There are 2 classes - ClassA and ClassB.

ClassA 除了里面的4个公共静态最终字符串值外什么也没有。它的目的是使用像 ClassA.variable 这样的值(不要问我为什么,这不是我的代码)。

ClassA has nothing except 4 public static final string values inside it. Its purpose is to use those values like ClassA.variable (don't ask me why, it's not my code).

ClassB 导入 ClassA 。我在 ClassA 中编辑了字符串值并进行了编译。当我运行 ClassB 时,我可以看到它使用的是旧值 - 而不是新值。我必须重新编译 ClassB 才能使用 ClassA 中的新值! (我不得不重新编译导入 ClassA 的其他类!)

ClassB imports ClassA. I edited the string values in ClassA and compiled it. When I ran ClassB I could see it was using the old values - not the new values. I had to recompile ClassB to make it use new values from ClassA! (I had to recompile other classes that imports ClassA!)

这只是因为JDK 1.6或我应该早先知道重新编译 ClassB 也!开导我。 :)

Is this just because of JDK 1.6 or I should have known earlier to recompile ClassB also! Enlighten me. :)

推荐答案

如果 final 的值来自类 ClassA 恰好是编译时常量,编译器可能已使用 ClassA 将它们内联到类中,而不是生成运行 - 时间参考。我想,这就是你所描述的情况。

If the values of the final variables from class ClassA happen to be compile-time constants, the compiler might have inlined them into the classes using ClassA instead of generating a run-time reference. I think, this is what happened in the case you described.

示例:

public class Flags {
    public static final int FOO = 1;
    public static final int BAR = 2;
}

public class Consumer {
    public static void main(String[] args) {
         System.out.println(Flags.FOO);
    }
}

在此示例中,编译器可能会合并值 FOO 进入为 Consumer 生成的代码,而不是生成等效的运行时引用。如果稍后更改 FOO 的值,则必须重新编译 Consumer 才能让它使用新价值。

In this example, the compiler will likely incorporate the value of FOO into the code generated for Consumer instead of generating the equivalent run-time reference. If the value of FOO changes later on, you will have to re-compile Consumer in order to have it use the new value.

这是一种优化,在编译程序的效率和速度方面具有一些优势。例如,内联值可能会在使用它的表达式中启用进一步优化,例如:

This is an optimization, which has a few advantages with respect to efficiency and speed of the program compiled. For example, inlining the value might enable further optimizations in the expressions, which use it, for example:

int x = Flags.FOO * 10;

在这个例子中,内联值(这里:1)使编译器能够注意到,乘法没有区别,可以一共省略。

In this example, inlining the value (here: 1) enables the compiler to notice, that the multiplication makes no difference, and can be omitted alltogether.

这篇关于导入的java类中的public static final变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:53