public static final variable in an imported java class

后端 未结 5 1280
故里飘歌
故里飘歌 2021-01-01 16:20

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

ClassA ha

5条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-01 17:03

    Suppose ClassA looks like this:

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

    If you recompile it, ClassB will continue using the old values. I guess it could depend on the compiler, but I think this is the typical behaviour. If you don't want to recompile ClassB everytime a constant in ClassA changes, you'll have to do something like this:

    public class ClassA {
        public static final int FOO = CONST(1);
        public static final int BAR = CONST(2);
    
        public static int CONST(int i) { return i; }
    }
    

    Becuase now javac is unwilling to inline the constants. Instead it will call the CONST(int) method when ClassA's static initializer runs.

提交回复
热议问题